File tree 5 files changed +76
-0
lines changed
5 files changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def countBits (self , n : int ) -> List [int ]:
3
+ counter = [0 ]
4
+
5
+ for i in range (1 , n + 1 ):
6
+ counter .append (counter [i >> 1 ] + i % 2 )
7
+
8
+ return counter
9
+
10
+ ## TC: O(n), SC: O(n)
11
+ ## this question should be under math section tbh
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
3
+ ans = collections .defaultdict (list )
4
+
5
+ for s in strs :
6
+ ans [str (sorted (s ))].append (s )
7
+
8
+ return list (ans .values ())
9
+
10
+ ## TC: O(n * klogk), SC: O(n * k), where n is len(strs) and k is len(longest_s)
11
+
12
+ # ans = {}
13
+
14
+ # for s in strs:
15
+ # sorted_s = ''.join(sorted(s))
16
+
17
+ # if sorted_s not in ans:
18
+ # ans[sorted_s] = []
19
+
20
+ # ans[sorted_s].append(s)
21
+
22
+ # return list(ans.values())
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def missingNumber (self , nums : List [int ]) -> int :
3
+ n = len (nums )
4
+
5
+ return int (n * (n + 1 ) / 2 - sum (nums ))
6
+
7
+ # TC: O(n), SC: O(1)
8
+ # this only works for "only missing number", if there are multiple missing numbers, this won't work
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def hammingWeight (self , n : int ) -> int :
3
+ counter = 0
4
+
5
+ while n :
6
+ counter += 1
7
+ n = n & (n - 1 )
8
+
9
+ return counter
10
+
11
+ ## TC: O(n), SC: O(1)
12
+
13
+ # counter = 0
14
+
15
+ # for i in bin(n):
16
+ # if i == "1":
17
+ # counter += 1
18
+
19
+ # return counter
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def reverseBits (self , n : int ) -> int :
3
+
4
+ res = 0
5
+
6
+ for i in range (32 ):
7
+ if n & 1 :
8
+ res += 1 << (31 - i )
9
+ n >>= 1
10
+
11
+ return res
12
+
13
+ # TC: O(1), SC: O(1) for both codes
14
+
15
+ # n = bin(n)[2:].zfill(32)
16
+ # return int(n[::-1], 2)
You can’t perform that action at this time.
0 commit comments