diff --git a/contains-duplicate/jungsiroo.py b/contains-duplicate/jungsiroo.py new file mode 100644 index 000000000..9ff59bc86 --- /dev/null +++ b/contains-duplicate/jungsiroo.py @@ -0,0 +1,18 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + # Slow - tc : O(n) / sc : O(1) + + """return len(set(nums)) != len(nums)""" + + # Fast - tc : O(n) / sc : O(n) + check = set() + + for num in nums: + if num in check: + return True + check.add(num) + + return False + + + diff --git a/house-robber/jungsiroo.py b/house-robber/jungsiroo.py new file mode 100644 index 000000000..ac721cab7 --- /dev/null +++ b/house-robber/jungsiroo.py @@ -0,0 +1,39 @@ +class Solution: + def bfs(self, nums): + from collections import deque + queue = deque() + + # price, idx, robbed prev + queue.append([0, 0, False]) + queue.append([0, 0, True]) + ret = 0 + + while queue: + price, idx, prev = queue.popleft() + ret = max(ret, price) + if idx == len(nums): + continue + + if prev: + queue.append([price, idx+1, False]) + else: + queue.append([price, idx+1, False]) + queue.append([price+nums[idx], idx+1, True]) + + return ret + + def rob(self, nums: List[int]) -> int: + # BFS - Slow and out of memory + """return self.bfs(nums)""" + + # DP + n = len(nums) + record = [[0]*n for _ in range(2)] + record[1][0] = nums[0] + + for i in range(1, n): + record[1][i] = max(record[0][i-1]+nums[i], record[1][i]) + record[0][i] = max(record[1][i-1], record[0][i-1]) + + return max(record[1][-1], record[0][-1]) + diff --git a/top-k-frequent-elements/jungsiroo.py b/top-k-frequent-elements/jungsiroo.py new file mode 100644 index 000000000..a60e117b1 --- /dev/null +++ b/top-k-frequent-elements/jungsiroo.py @@ -0,0 +1,26 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + # Naive Solution + # TC : O(nlogn) + # SC : O(n) + + cnt = dict() + for num in nums: + cnt[num] = cnt.get(num, 0) + 1 + + """ + ret = dict(sorted(cnt.items(), key=lambda x:(-x[1], x[0]))) + return list(ret.keys())[:k] + """ + + # Follow up Solution + # TC : O(nlog(k)) + # SC : O(n) + + import heapq + + ret = [(-c, num) for num, c in cnt.items()] + heapq.heapify(ret) + + return [heapq.heappop(ret)[1] for _ in range(k)] + diff --git a/valid-palindrome/jungsiroo.py b/valid-palindrome/jungsiroo.py new file mode 100644 index 000000000..87dfa11f9 --- /dev/null +++ b/valid-palindrome/jungsiroo.py @@ -0,0 +1,7 @@ +import re + +class Solution: + def isPalindrome(self, s: str) -> bool: + # Fastest - tc : O(n) / sc : O(1 + s = ''.join(re.findall(r'[a-z0-9]+', s.lower())) + return s == ''.join(reversed(s))