Tensorum
YouTubeसीखना शुरू करें
LeetCode 75 · Two Pointers

Sort Colors

LeetCode 75 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

low / mid / high pointers partition into 0s, 1s, 2s in one pass.

मध्यमArrayTwo PointersSortingQuicksortBubble Sort

मैंने 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. 1

    0 at mid: swap with low, advance both.

  2. 2

    1 at mid: just advance mid.

  3. 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.