Skip to content

Commit 1b02799

Browse files
author
Mauricio Klein
committed
Add solution for challenge #59
1 parent 72c58fb commit 1b02799

File tree

6 files changed

+64
-0
lines changed

6 files changed

+64
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,4 @@
5858
- [x] [Challenge 56: Find largest BST](challenge-56/)
5959
- [x] [Challenge 57: Arithmetic Binary Tree](challenge-57/)
6060
- [x] [Challenge 58: Get all Values at a Certain Height in a Binary Tree](challenge-58/)
61+
- [x] [Challenge 59: Sort Colors](challenge-59/)

challenge-59/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-59/README.md

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Sort Colors
2+
3+
This problem was asked by Apple.
4+
5+
## Description
6+
7+
Given an array 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.
8+
9+
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
10+
11+
Note: You are not suppose to use the library’s sort function for this problem.
12+
13+
Can you do it in a single pass?
14+
15+
## Example
16+
17+
```
18+
Input: [2, 0, 2, 1, 1, 0]
19+
Output: [0, 0, 1, 1, 2, 2]
20+
```

challenge-59/__init__.py

Whitespace-only changes.

challenge-59/solver.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#
2+
# Time complexity: O(n)
3+
# Space complexity: O(1) (sort performed in place)
4+
#
5+
def sort_colors(colors):
6+
def swap(i, j):
7+
colors[i], colors[j] = colors[j], colors[i]
8+
9+
left, right = 0, len(colors) - 1
10+
i = 0
11+
12+
while i <= right:
13+
if colors[i] == 0:
14+
swap(i, left)
15+
left += 1
16+
i += 1
17+
elif colors[i] == 2:
18+
swap(i, right)
19+
right -= 1
20+
else:
21+
i += 1
22+
23+
return colors

challenge-59/test_solver.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import unittest
2+
import solver
3+
from solver import sort_colors
4+
5+
class TestSolver(unittest.TestCase):
6+
def test_sort_colors(self):
7+
self.assertEqual(sort_colors([0, 0, 0, 0, 0, 0]), [0, 0, 0, 0, 0, 0])
8+
self.assertEqual(sort_colors([2, 2, 2, 2, 2, 2]), [2, 2, 2, 2, 2, 2])
9+
self.assertEqual(sort_colors([0, 0, 2, 0, 0, 0]), [0, 0, 0, 0, 0, 2])
10+
self.assertEqual(sort_colors([0, 0, 0, 0, 1, 0]), [0, 0, 0, 0, 0, 1])
11+
self.assertEqual(sort_colors([2, 2, 1, 2, 2, 2]), [1, 2, 2, 2, 2, 2])
12+
self.assertEqual(sort_colors([0, 2, 2, 0, 2, 0]), [0, 0, 0, 2, 2, 2])
13+
self.assertEqual(sort_colors([2, 0, 2, 1, 1, 0]), [0, 0, 1, 1, 2, 2])
14+
15+
if __name__ == "__main__":
16+
unittest.main()

0 commit comments

Comments
 (0)