diff --git a/contains-duplicate/Raft.py b/contains-duplicate/Raft.py new file mode 100644 index 000000000..bd5f51287 --- /dev/null +++ b/contains-duplicate/Raft.py @@ -0,0 +1,12 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + appeared = defaultdict(int) + for n in nums: + if appeared[n] > 0: + return True + appeared[n] += 1 + + return False +# T: O(n) +# S: O(n) + diff --git a/kth-smallest-element-in-a-bst/Raft.py b/kth-smallest-element-in-a-bst/Raft.py new file mode 100644 index 000000000..5b21826f2 --- /dev/null +++ b/kth-smallest-element-in-a-bst/Raft.py @@ -0,0 +1,16 @@ +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + stack = [] + + while True: + while root: + stack.append(root) + root = root.left + root = stack.pop() + k -= 1 + if not k: + return root.val + root = root.right +# T: O(n) +# S: O(n) + diff --git a/number-of-1-bits/Raft.py b/number-of-1-bits/Raft.py new file mode 100644 index 000000000..48f74fa8c --- /dev/null +++ b/number-of-1-bits/Raft.py @@ -0,0 +1,10 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + res = 0 + while n: + res += n % 2 + n = n >> 1 + return res +# T: logn +# S: 1 + diff --git a/palindromic-substrings/Raft.py b/palindromic-substrings/Raft.py new file mode 100644 index 000000000..904f9075f --- /dev/null +++ b/palindromic-substrings/Raft.py @@ -0,0 +1,18 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + count = 0 + for i in range(len(s)): + count += self.countPalindrome(s, i, i) + count += self.countPalindrome(s, i, i + 1) + return count + + def countPalindrome(self, s, l, r): + count = 0 + while r < len(s) and l >= 0 and s[l] == s[r]: + count += 1 + l -= 1 + r += 1 + return count +# T: O(n^2) +# S: O(n^2) + diff --git a/top-k-frequent-elements/raft.py b/top-k-frequent-elements/raft.py new file mode 100644 index 000000000..a92f75ece --- /dev/null +++ b/top-k-frequent-elements/raft.py @@ -0,0 +1,44 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + # Frequency + freq = defaultdict(int) + for n in nums: + freq[n] += 1 + + freq_list = [] + for key, val in freq.items(): + freq_list.append((-1 * val, key)) + + heapq.heapify(freq_list) + + res = [] + for _ in range(k): + res.append(heapq.heappop(freq_list)[1]) + + return res + + # T: nlogn + # S: n + + def topKFrequent2(self, nums: List[int], k: int) -> List[int]: + res = [] + # Frequency + count = defaultdict(int) + for n in nums: + count[n] += 1 + + # Convert to frequency + frequency = [[] for _ in range(len(nums) + 1)] + for key, freq in count.items(): + frequency[freq].append(key) + + # top K + for freq in range(len(nums), 0, -1): + for n in frequency[freq]: + res.append(n) + + if len(res) == k: + return res + # T: n + # S: n +