Skip to content

Commit 139d02e

Browse files
author
Mauricio Klein
committed
Add solution for challenge #53
1 parent d05b350 commit 139d02e

File tree

6 files changed

+60
-0
lines changed

6 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,4 @@
5252
- [x] [Challenge 50: Create a balanced binary search tree](challenge-50/)
5353
- [x] [Challenge 51: Subsequences of string](challenge-51/)
5454
- [x] [Challenge 52: Deepest Node in a Binary Tree](challenge-52/)
55+
- [x] [Challenge 53: Thousand missing numbers](challenge-53/)

challenge-53/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-53/README.md

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Thousand missing numbers
2+
3+
This problem was asked by Two Sigma.
4+
5+
## Description
6+
7+
You are given an unsorted list of 999,000 unique integers, each from 1 and 1,000,000. Find the missing 1000 numbers.
8+
9+
What is the computational and space complexity of your solution?

challenge-53/__init__.py

Whitespace-only changes.

challenge-53/solver.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#
2+
# Time complexity : O(n) (every elements is swapped at most once)
3+
# Space complexity: O(1000000) (constant one million, for the extended array)
4+
#
5+
def first_thousand_missing(nums):
6+
# Extend the array to length 1M, filling with "None"
7+
diff = 1000000 - len(nums)
8+
nums.extend([None for _ in range(diff)])
9+
10+
# Put the elements in the right position (i.e. nums[i] = i+1)
11+
# If find a "None", skip it)
12+
for i in range(len(nums)):
13+
while nums[i] != None and nums[i] != i+1:
14+
num = nums[i]
15+
nums[i], nums[num - 1] = nums[num - 1], nums[i]
16+
17+
# Iterate over the nums and, when find a "None", means
18+
# the element at the position is missing
19+
missing = []
20+
for i in range(len(nums)):
21+
if nums[i] == None:
22+
missing.append(i+1)
23+
24+
return missing

challenge-53/test_solver.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import unittest, random
2+
from solver import first_thousand_missing
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_first_thousand_missing(self):
6+
nums = range(1,1000001)
7+
missing = random.sample(nums, 1000)
8+
9+
# Remove the missing values from the array
10+
for num in missing:
11+
nums.remove(num)
12+
13+
# Shuffle the array
14+
random.shuffle(nums)
15+
16+
# Sort the missing values
17+
missing.sort()
18+
19+
self.assertEqual(first_thousand_missing(nums), missing)
20+
21+
if __name__ == "__main__":
22+
unittest.main()

0 commit comments

Comments
 (0)