diff --git a/contains-duplicate/hajunyoo.py b/contains-duplicate/hajunyoo.py new file mode 100644 index 000000000..058172a4b --- /dev/null +++ b/contains-duplicate/hajunyoo.py @@ -0,0 +1,7 @@ +class Solution: + # Time complexity: O(n) + def containsDuplicate(self, nums: List[int]) -> bool: + string_len = len(nums) + set_len = len(set(nums)) + + return string_len != set_len diff --git a/kth-smallest-element-in-a-bst/hajunyoo.py b/kth-smallest-element-in-a-bst/hajunyoo.py new file mode 100644 index 000000000..3deb0e4a6 --- /dev/null +++ b/kth-smallest-element-in-a-bst/hajunyoo.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +from collections import defaultdict + + +class Solution: + # Time complexity: O(n) + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + self.count = 0 + self.result = 0 + + def dfs(node): + if not node: + return + + dfs(node.left) + + self.count += 1 + if self.count == k: + self.result = node.val + return + + dfs(node.right) + + dfs(root) + return self.result diff --git a/number-of-1-bits/hajunyoo.py b/number-of-1-bits/hajunyoo.py new file mode 100644 index 000000000..b8e0e07fc --- /dev/null +++ b/number-of-1-bits/hajunyoo.py @@ -0,0 +1,9 @@ +class Solution: + # Time complexity: O(log n) + def hammingWeight(self, n: int) -> int: + cnt = 0 + while n > 0: + if n % 2 == 1: + cnt += 1 + n = n // 2 + return cnt diff --git a/palindromic-substrings/hajunyoo.py b/palindromic-substrings/hajunyoo.py new file mode 100644 index 000000000..08982c61b --- /dev/null +++ b/palindromic-substrings/hajunyoo.py @@ -0,0 +1,19 @@ +class Solution: + # Time complexity: O(n^2) = O(n) * O(n) + def countSubstrings(self, s: str) -> int: + self.count = 0 + n = len(s) + + def two_pointer_expand(left, right): + while left >= 0 and right < n and s[left] == s[right]: + self.count += 1 + left -= 1 + right += 1 + + for i in range(0, n): + # 1, 3, 5 ... + two_pointer_expand(i, i) + # 2, 4, 6 ... + two_pointer_expand(i, i + 1) + + return self.count diff --git a/top-k-frequent-elements/hajunyoo.py b/top-k-frequent-elements/hajunyoo.py new file mode 100644 index 000000000..a26351c77 --- /dev/null +++ b/top-k-frequent-elements/hajunyoo.py @@ -0,0 +1,20 @@ +from collections import defaultdict +from typing import List + + +class Solution: + # Time complexity: O(nlogn) -> O(n) + O(nlogn) + O(k) + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + counter_dict = defaultdict(int) + + for n in nums: + counter_dict[n] += 1 + + count_list = [] + for key, val in counter_dict.items(): + count_list.append((key, val)) + + count_list.sort(key=lambda x: x[1], reverse=True) + answer = [a for a, b in count_list[:k]] + + return answer