Sort Colors
LeetCode 75 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
low / mid / high pointers partition into 0s, 1s, 2s in one pass.
আমি Sort Colors (LeetCode 75) এভাবে সমাধান করেছি — Two Pointers প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Dutch national flag: keep three regions — 0s on the left of low, 2s on the right of high, and 1s in between. mid scans the unknown part and sends 0s left and 2s right with swaps.
Approach
- 1
0 at mid: swap with low, advance both.
- 2
1 at mid: just advance mid.
- 3
2 at mid: swap with high and shrink high (don't advance mid — the swapped-in value is unchecked).
আমি কীভাবে সমাধান করেছি
Dutch national flagPythonO(n) time · O(1) space
class Solution:
def sortColors(self, nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
low=0
mid = 0
high = len(nums)-1
while mid<=high:
if nums[mid]==0:
#move left
nums[low],nums[mid]=nums[mid],nums[low]
#increase right boundary of 0
low+=1
mid+=1
elif nums[mid]==1:
#no worries
mid+=1
elif nums[mid]==2:
nums[mid],nums[high]=nums[high],nums[mid]
#increase the left boundary of 2
high-=1
Sort Colors — সাধারণ প্রশ্ন
Sort Colors-এর পেছনে intuition কী?
Dutch national flag: keep three regions — 0s on the left of low, 2s on the right of high, and 1s in between. mid scans the unknown part and sends 0s left and 2s right with swaps.
Sort Colors (LeetCode 75) কীভাবে সমাধান করবেন?
1. 0 at mid: swap with low, advance both. 2. 1 at mid: just advance mid. 3. 2 at mid: swap with high and shrink high (don't advance mid — the swapped-in value is unchecked).
Sort Colors-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Dutch national flag।)
Sort Colors-এ সাধারণ ভুলগুলো কী?
Don't increment mid after swapping with high.