Medium
Sort Colors
- Time limit
- 2 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Sorting Algorithms
Description
Description
Given an array nums with n elements where each element is exactly 0, 1, or 2, sort the array in ascending order and return it.
The sort must be in-place in spirit: the returned array must contain the same values sorted, and only these three values may appear in the result. You should solve it in a single pass if possible.
Examples
Example 1
- Input:
nums = [2, 0, 2, 1, 1, 0] - Output:
[0, 0, 1, 1, 2, 2]
Example 2
- Input:
nums = [2, 0, 1] - Output:
[0, 1, 2]
Example 3
- Input:
nums = [0] - Output:
[0]
Expected Function Behavior
Implement sortColors(nums) and return the sorted array.
Constraints
1 <= nums.length <= 1000nums[i]is0,1, or2.- The returned array must be sorted in ascending order.
Sample cases
3Sample 1
Input
nums = [2,0,2,1,1,0]
Expected output
[0,0,1,1,2,2]
Sample 2
Input
nums = [2,0,1]
Expected output
[0,1,2]
Skills and languages
Patterns
- Dutch National Flag Partitioning
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer