Skip to content

Commit 956c04b

Browse files
committed
Done up to #5
1 parent e8594cb commit 956c04b

14 files changed

+97
-157
lines changed

problems/01/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
##Problem 1
1+
## Problem 1
22

33
Given a stack of N elements, interleave the first half of the stack
44
with the second half reversed using one other queue.
5+
56
Example:
67

78
>>> coding_problem_01([1, 2, 3, 4, 5])

problems/01/solution_01.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ def coding_problem_01(stack):
1515
Note: with itertools, you could instead islice(chain.from_iterable(izip(l, reversed(l))), len(l))
1616
"""
1717
queue = deque([]) # stack S:[1,2,3,4,5], queue Q:[]
18-
for cnt in range(len(stack) - 1): # move stack into queue. S:[1], Q:[5,4,3,2]
18+
for _ in range(len(stack) - 1): # move stack into queue. S:[1], Q:[5,4,3,2]
1919
queue.append(stack.pop())
20-
for cnt in range(len(queue) // 2):
20+
for _ in range(len(queue) // 2):
2121
stack.append(queue.popleft()) # S:[1,5], Q:[4,3,2]
22-
for cnt2 in range(len(queue) - 1): # rotate last element to front, S:[1,5], Q:[2,4,3]
22+
for __ in range(len(queue) - 1): # rotate last element to front, S:[1,5], Q:[2,4,3]
2323
queue.append(queue.popleft())
2424
stack.append(queue.popleft()) # S:[1,5,2], Q:[4,3]
2525
if queue:

problems/02/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
##Problem 2
1+
## Problem 2
22

33
Given an array of integers, return a new array such that each element at index i of
44
the new array is the product of all the numbers in the original array except the one at i.
55
Solve it without using division and in O(n).
6+
67
Example:
78

89
>>> coding_problem_02([1, 2, 3, 4, 5])

problems/02/problem_02.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
from collections import deque
2-
3-
41
def coding_problem_02(l):
52
"""
63
Given an array of integers, return a new array such that each element at index i of

problems/02/solution_02.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
from collections import deque
2-
3-
41
def coding_problem_02(l):
52
"""
63
Given an array of integers, return a new array such that each element at index i of
@@ -13,7 +10,7 @@ def coding_problem_02(l):
1310
"""
1411
forward = [1] * len(l)
1512
backward = [1] * len(l)
16-
for idx in xrange(1, len(l)):
13+
for idx in range(1, len(l)):
1714

1815
forward[idx] = forward[idx - 1] * l[idx - 1]
1916
backward[-idx - 1] = backward[-idx] * l[-idx]

problems/03/README.md

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
##Problem 3
1+
## Problem 3
22

33
Given the root to a binary tree, implement serialize(root), which serializes the tree
44
into a string, and deserialize(s), which deserializes the string back into the tree.
5+
56
Example:
67

7-
>>> s = '3 2 1 None None None 4 5 None None 6 None None'
8-
>>> de_serialized = coding_problem_03(s)
9-
>>> re_serialized = de_serialized.serialize_to_string()
10-
>>> s == re_serialized
11-
True
8+
>>> serialize, deserialize = coding_problem_03()
9+
>>> s = '>>> YOUR OWN TREE ENCODING HERE <<<'
10+
>>> isinstance(s, str)
11+
True
12+
13+
>>> s == serialize(deserialize(s))
14+
True

problems/03/problem_03.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1-
from collections import deque
2-
3-
4-
def coding_problem_03(s):
1+
def coding_problem_03():
52
"""
63
Given the root to a binary tree, implement serialize(root), which serializes the tree
7-
into a string, and deserialize(s), which deserializes the string back into the tree.
4+
into a string, and deserialize(s), which de-serializes the string back into the tree.
85
Example:
96
10-
>>> s = '3 2 1 None None None 4 5 None None 6 None None'
11-
>>> de_serialized = coding_problem_03(s)
12-
>>> re_serialized = de_serialized.serialize_to_string()
13-
>>> s == re_serialized
7+
>>> serialize, deserialize = coding_problem_03()
8+
>>> s = '>>> YOUR OWN TREE ENCODING HERE <<<'
9+
>>> isinstance(s, str)
10+
True
11+
12+
>>> s == serialize(deserialize(s))
1413
True
1514
"""
1615
pass

problems/03/solution_03.py

Lines changed: 31 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,43 @@
1-
from collections import deque
1+
from typing import Iterable
22

33

4-
def coding_problem_03(s):
4+
def coding_problem_03():
55
"""
66
Given the root to a binary tree, implement serialize(root), which serializes the tree
7-
into a string, and deserialize(s), which deserializes the string back into the tree.
7+
into a string, and deserialize(s), which de-serializes the string back into the tree.
88
Example:
99
10+
>>> serialize, deserialize = coding_problem_03()
1011
>>> s = '3 2 1 None None None 4 5 None None 6 None None'
11-
>>> de_serialized = coding_problem_03(s)
12-
>>> re_serialized = de_serialized.serialize_to_string()
13-
>>> s == re_serialized
12+
>>> tree = (3, (2, (1, None, None), None), (4, (5, None, None), (6, None, None)))
13+
>>> isinstance(s, str)
1414
True
15+
16+
>>> deserialized = deserialize(s)
17+
>>> tree == deserialized
18+
True
19+
20+
>>> s == serialize(deserialized)
21+
True
22+
23+
Notes: the implementation below tries to solve the problem as intended.
24+
However, one could instead: serialize, deserialize = lambda tree: repr(tree), lambda s: eval(s)
1525
"""
16-
class BinaryNode(object):
17-
18-
def __init__(self, val, lc=None, rc=None):
19-
self.val = val
20-
self.lc = lc
21-
self.rc = rc
22-
23-
def serialize(self, queue=None):
24-
queue = [] if queue is None else queue
25-
queue.append(self.val)
26-
if self.val is not None:
27-
self.lc.serialize(queue)
28-
self.rc.serialize(queue)
29-
return queue
30-
31-
@classmethod
32-
def deserialize(cls, queue):
33-
val, lc, rc = queue.pop(), None, None
34-
if val is not None:
35-
lc = cls.deserialize(queue)
36-
rc = cls.deserialize(queue)
37-
return BinaryNode(val, lc, rc)
38-
39-
def serialize_to_string(self):
40-
return ' '.join(repr(element) for element in self.serialize())
41-
42-
@classmethod
43-
def deserialize_from_string(cls, s):
44-
return cls.deserialize([int(token) if token != 'None' else None for token in s.split(' ')][::-1])
45-
46-
return BinaryNode.deserialize_from_string(s)
26+
def deserialize_array(array):
27+
val = array.pop()
28+
return None if val is None else (val, deserialize_array(array), deserialize_array(array))
29+
30+
def flatten(array):
31+
return [y for x in array for y in flatten(x)] if isinstance(array, Iterable) else [array]
32+
33+
def serialize(array):
34+
return ' '.join(repr(element) for element in flatten(array))
35+
36+
def deserialize(s):
37+
values = [int(token) if token != 'None' else None for token in s.split()]
38+
return deserialize_array(values[::-1])
39+
40+
return serialize, deserialize
4741

4842

4943
if __name__ == '__main__':

problems/04/README.md

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,15 @@
1-
##Problem 4
1+
## Problem 4
22

33
Given an array of integers, find the first missing positive integer in linear time and constant space.
44
You can modify the input array in-place.
5+
56
Example:
67

78
>>> coding_problem_04([3, 4, -1, 1])
89
2
10+
911
>>> coding_problem_04([1, 2, 0])
1012
3
13+
1114
>>> coding_problem_04([4, 1, 2, 2, 2, 1, 0])
1215
3
13-
14-
Notes: the code below is a bucket sort variant, and therefore has linear time complexity equal to O(n).
15-
More in detail, all the for loops in the code are O(n). The while loop is also linear, because it loops
16-
only when element are not ordered and each iteration correctly positions one element of the array.
17-
18-
This was my original implementation, which however is not constant space:
19-
20-
bucket_sort = [True] + [False] * len(arr) # skip 0 index
21-
for element in filter(lambda x: 0 < x < len(arr), arr):
22-
bucket_sort[element] = True
23-
return bucket_sort.index(False)
24-
25-
The following one, also not constant space but possibly more understandable,
26-
has been contributed by NikhilCodes (https://github.com/NikhilCodes):
27-
28-
arr = set(arr) # O(n)
29-
max_val = max(arr) # O(n)
30-
missing_val = max_val + 1
31-
for e in range(1, max_val + 1): # O(n)
32-
if e not in arr: # O(1)
33-
missing_val = e
34-
break
35-
return missing_val

problems/04/problem_04.py

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
from collections import deque
2-
3-
41
def coding_problem_04(array):
52
"""
63
Given an array of integers, find the first missing positive integer in linear time and constant space.
@@ -13,29 +10,6 @@ def coding_problem_04(array):
1310
3
1411
>>> coding_problem_04([4, 1, 2, 2, 2, 1, 0])
1512
3
16-
17-
Notes: the code below is a bucket sort variant, and therefore has linear time complexity equal to O(n).
18-
More in detail, all the for loops in the code are O(n). The while loop is also linear, because it loops
19-
only when element are not ordered and each iteration correctly positions one element of the array.
20-
21-
This was my original implementation, which however is not constant space:
22-
23-
bucket_sort = [True] + [False] * len(arr) # skip 0 index
24-
for element in filter(lambda x: 0 < x < len(arr), arr):
25-
bucket_sort[element] = True
26-
return bucket_sort.index(False)
27-
28-
The following one, also not constant space but possibly more understandable,
29-
has been contributed by NikhilCodes (https://github.com/NikhilCodes):
30-
31-
arr = set(arr) # O(n)
32-
max_val = max(arr) # O(n)
33-
missing_val = max_val + 1
34-
for e in range(1, max_val + 1): # O(n)
35-
if e not in arr: # O(1)
36-
missing_val = e
37-
break
38-
return missing_val
3913
"""
4014
pass
4115

0 commit comments

Comments
 (0)