Backlog·queued
Sort Colors
DifficultyMedium
PatternTwo Pointers
TrackDSA
tl;dr
Sort the array in place so that the elements of the same color are adjacent, with the colors in the order of red, white, and blue. The function should return the same array.
full write-up
Statement
Given an array, colors, which contains a combination of the following three elements:
0(representing red)1(representing white)2(representing blue)
Sort the array in place so that the elements of the same color are adjacent, with the colors in the order of red, white, and blue. The function should return the same array.
Note: The function should only return the modified
colorsarray.
Constraints
- 1 ≤
colors.length≤ 300 colors[i]can only contain0s,1s, or2s.
Examples
Example 1
Input: colors = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Example 2
Input: colors = [2, 0, 1]
Output: [0, 1, 2]