File tree Expand file tree Collapse file tree 5 files changed +100
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 5 files changed +100
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def containsDuplicate (self , nums : List [int ]) -> bool :
3+ appeared = defaultdict (int )
4+ for n in nums :
5+ if appeared [n ] > 0 :
6+ return True
7+ appeared [n ] += 1
8+
9+ return False
10+ # T: O(n)
11+ # S: O(n)
12+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def kthSmallest (self , root : Optional [TreeNode ], k : int ) -> int :
3+ stack = []
4+
5+ while True :
6+ while root :
7+ stack .append (root )
8+ root = root .left
9+ root = stack .pop ()
10+ k -= 1
11+ if not k :
12+ return root .val
13+ root = root .right
14+ # T: O(n)
15+ # S: O(n)
16+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def hammingWeight (self , n : int ) -> int :
3+ res = 0
4+ while n :
5+ res += n % 2
6+ n = n >> 1
7+ return res
8+ # T: logn
9+ # S: 1
10+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def countSubstrings (self , s : str ) -> int :
3+ count = 0
4+ for i in range (len (s )):
5+ count += self .countPalindrome (s , i , i )
6+ count += self .countPalindrome (s , i , i + 1 )
7+ return count
8+
9+ def countPalindrome (self , s , l , r ):
10+ count = 0
11+ while r < len (s ) and l >= 0 and s [l ] == s [r ]:
12+ count += 1
13+ l -= 1
14+ r += 1
15+ return count
16+ # T: O(n^2)
17+ # S: O(n^2)
18+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
3+ # Frequency
4+ freq = defaultdict (int )
5+ for n in nums :
6+ freq [n ] += 1
7+
8+ freq_list = []
9+ for key , val in freq .items ():
10+ freq_list .append ((- 1 * val , key ))
11+
12+ heapq .heapify (freq_list )
13+
14+ res = []
15+ for _ in range (k ):
16+ res .append (heapq .heappop (freq_list )[1 ])
17+
18+ return res
19+
20+ # T: nlogn
21+ # S: n
22+
23+ def topKFrequent2 (self , nums : List [int ], k : int ) -> List [int ]:
24+ res = []
25+ # Frequency
26+ count = defaultdict (int )
27+ for n in nums :
28+ count [n ] += 1
29+
30+ # Convert to frequency
31+ frequency = [[] for _ in range (len (nums ) + 1 )]
32+ for key , freq in count .items ():
33+ frequency [freq ].append (key )
34+
35+ # top K
36+ for freq in range (len (nums ), 0 , - 1 ):
37+ for n in frequency [freq ]:
38+ res .append (n )
39+
40+ if len (res ) == k :
41+ return res
42+ # T: n
43+ # S: n
44+
You can’t perform that action at this time.
0 commit comments