Skip to content

Commit 343f7cd

Browse files
Leetcode 75
1 parent a9752d8 commit 343f7cd

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Leetcode/Leetcode_75.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def sortColors(self, nums: List[int]) -> None:
3+
"""
4+
Sorts an array containing only 0s, 1s, and 2s in-place
5+
using the Dutch National Flag Algorithm.
6+
Time Complexity: O(n)
7+
Space Complexity: O(1)
8+
"""
9+
10+
# Pointer for the next position of 0
11+
low = 0
12+
13+
# Pointer for the next position of 2
14+
high = len(nums) - 1
15+
16+
# Current element being processed
17+
mid = 0
18+
19+
while mid <= high:
20+
if nums[mid] == 0:
21+
# Place 0 at the beginning section
22+
nums[low], nums[mid] = nums[mid], nums[low]
23+
low += 1
24+
mid += 1
25+
26+
elif nums[mid] == 1:
27+
# 1 is already in the correct section
28+
mid += 1
29+
30+
else:
31+
# Place 2 at the ending section
32+
nums[mid], nums[high] = nums[high], nums[mid]
33+
high -= 1
34+
35+
return nums

0 commit comments

Comments
 (0)