AceYourInterviews
Checking sign-in…

12. Sort Colors

IntermediateDutch-national-flag partition

Rearrange the input so every 0 comes before every 1, and every 1 comes before every 2. The task concerns these three categories and must be completed without calling a comparison-based sort.

Keep the same array object and retain every occurrence. Values outside the permitted categories are covered by the precise input contract below.

Example 1

Input

[2,0,2,1,1,0]

Output

[0,0,1,1,2,2]

Explanation: Every occurrence is partitioned by its bounded key.

Example 2

Input

[2,0,1]

Output

[0,1,2]

Explanation: A swap from the high end can bring an unknown value into mid.

Constraints

  • 0 <= nums.length <= 105
  • nums[i] is 0, 1 or 2
Hints
Hint 1

Separate the processed values from an unknown interval.

Hint 2

Which swap brings a known value back, and which brings an unknown one?

Hint 3

Use low/mid/high and recheck mid after swapping with high.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Unknown values swapped in from high

[2,0,2,1,1,0]
[0,0,1,1,2,2]