Solved "Sort Colors" problem on LeetCode using Dutch National Flag Algorithm

Solved "Sort Colors" on LeetCode I remember solving this before as “Sort 0/1/2”. This time I tried from memory, then checked my old notes to fix a missing detail. Problem : Sort an array of 0s, 1s, and 2s in-place in a single pass & O(1) space. Approach — Dutch National Flag Algorithm We use 3 pointers: • low → for 0s which starts from 0th index. • mid → for current element • high → for 2s which starts from last index. Logic: If Element is 0 : • It belongs to the front → swap with `low` • We increase both `low` and `mid`   Because we are sure the swapped element is 1 (already checked earlier) If Element is 2 : • It belongs to the end → swap with `high` • Only decrease `high`   Because the swapped element might be 0 or 1, so we must recheck this index → don’t move mid • If Element is 1 : just move mid ahead This gradually pushes all 0s to the left and 2s to the right #LearnInPublic #LeetCode #Java #PlacementPrep #DSA Code (Java):

  • text

To view or add a comment, sign in

Explore content categories