File tree 3 files changed +83
-0
lines changed
longest-repeating-character-replacement
3 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments