Skip to content

Commit 82a90a5

Browse files
authored
Merge pull request #1502 from i-mprovising/main
[i-mprovising] Week 08 solutions
2 parents 01f4232 + 6c90217 commit 82a90a5

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

clone-graph/i-mprovising.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Time complexity O(V + E)
3+
Space complexity O(V + E)
4+
5+
DFS, BFS
6+
"""
7+
from collections import deque
8+
9+
class Solution:
10+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
11+
# dfs
12+
if not node:
13+
return
14+
15+
clone = Node(node.val)
16+
graph = {node:clone}
17+
stack = [node]
18+
19+
while stack:
20+
node = stack.pop()
21+
for n in node.neighbors:
22+
if n not in graph:
23+
stack.append(n)
24+
graph[n] = Node(n.val)
25+
graph[node].neighbors.append(graph[n])
26+
27+
return clone
28+
29+
def bfs(self, node):
30+
if not node:
31+
return
32+
33+
clone = Node(node.val) # clone first node
34+
clones = {node: clone} # reference node : clone node
35+
queue = deque([node])
36+
while queue:
37+
node = queue.popleft()
38+
for nei in node.neighbors:
39+
if nei not in clones:
40+
clones[nei] = Node(nei.val) # clone node
41+
queue.append(nei) # append queue neighbor reference node
42+
clones[node].neighbors.append(clones[nei])
43+
return clone
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from collections import defaultdict
2+
3+
class Solution:
4+
def characterReplacement(self, s: str, k: int) -> int:
5+
"""
6+
Time complexity O(n)
7+
Space complexity O(1)
8+
9+
Sliding window
10+
"""
11+
start, end = 0, 0
12+
window = defaultdict(int)
13+
max_len = 0
14+
15+
while end < len(s):
16+
window[s[end]] += 1
17+
while end-start+1 - max(window.values()) > k:
18+
window[s[start]] -= 1
19+
start += 1
20+
# move idx
21+
max_len = max(max_len, end-start+1)
22+
end += 1
23+
24+
return max_len

reverse-bits/i-mprovising.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
"""
3+
Time, space complexity O(1)
4+
"""
5+
def reverseBits(self, n: int) -> int:
6+
stack = []
7+
while len(stack) < 32:
8+
stack.append(n % 2)
9+
n //= 2
10+
11+
reverse, x = 0, 1
12+
while stack:
13+
reverse += stack.pop() * x
14+
x *= 2
15+
16+
return reverse

0 commit comments

Comments
 (0)