Sort Colors — LeetCode 75 Python Solution
- Problem
- #75
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Example
- Input
- nums = [2,0,2,1,1,0]
- Output
- [0,0,1,1,2,2]
Python solution
class Solution:
def sortColors(self, nums: List[int]) -> None:
i, j, k = -1, len(nums), 0
while k < j:
if nums[k] == 0:
i += 1
nums[i], nums[k] = nums[k], nums[i]
k += 1
elif nums[k] == 2:
j -= 1
nums[j], nums[k] = nums[k], nums[j]
else:
k += 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 75. Sort Colors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On a study list
This problem is on Grind 75.
Frequently asked questions
- How hard is LeetCode 75. Sort Colors?
- LeetCode 75. Sort Colors is rated Medium on LeetCode.
- What is the time complexity of LeetCode 75. Sort Colors?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 75. Sort Colors?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 75. Sort Colors cover?
- LeetCode 75. Sort Colors is tagged Array, Two Pointers and Sorting on LeetCode.