diff --git a/longest-consecutive-sequence/sun912.py b/longest-consecutive-sequence/sun912.py new file mode 100644 index 000000000..a02be4a51 --- /dev/null +++ b/longest-consecutive-sequence/sun912.py @@ -0,0 +1,19 @@ +""" +TC: O(n) +SC: O(n) +""" + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + longest = 0 + num_set = set(nums) + print(num_set) + + for n in num_set: + if (n-1) not in num_set: + length = 1 + while (n+length) in num_set: + length += 1 + longest = max(longest, length) + + return longest diff --git a/maximum-product-subarray/sun912.py b/maximum-product-subarray/sun912.py new file mode 100644 index 000000000..a557bb95f --- /dev/null +++ b/maximum-product-subarray/sun912.py @@ -0,0 +1,15 @@ +""" + TC: O(n) + SC: O(1) +""" +class Solution: + def maxProduct(self, nums: List[int]) -> int: + minimum, maximum = 1, 1 + result = nums[0] + + for num in nums: + minimum, maximum = min(minimum * num, maximum * num, num), max(minimum * num, maximum * num, num) + result = max(maximum, result) + + return result + diff --git a/missing-number/sun912.py b/missing-number/sun912.py new file mode 100644 index 000000000..805e520b1 --- /dev/null +++ b/missing-number/sun912.py @@ -0,0 +1,12 @@ +""" +TC: O(n) +SC: O(n) +""" + +class Solution: + def missingNumber(self, nums: List[int]) -> int: + nums_set = set(nums) + for i in range(len(nums)): + if i not in nums_set: + return i + return len(nums) diff --git a/valid-palindrome/sun912.py b/valid-palindrome/sun912.py new file mode 100644 index 000000000..929857284 --- /dev/null +++ b/valid-palindrome/sun912.py @@ -0,0 +1,22 @@ +""" +TC: O(n) +SC: O(n) +""" +class Solution: + def isPalindrome(self, s: str) -> bool: + str = list(s.lower()) + chars = [] + for c in str: + if (ord(c) >= ord("a") and ord(c) <= ord("z")) or (ord(c) >= ord("0") and ord(c) <= ord("9")): + chars.append(c) + + for i in range(len(chars)//2): + + if len(c)%2 == 0: + if chars[i] != chars[-(i+1)]: + return False + else: + if chars[i] != chars[-(i+1)]: + return False + + return True diff --git a/word-search/sun912.py b/word-search/sun912.py new file mode 100644 index 000000000..2f36b73dd --- /dev/null +++ b/word-search/sun912.py @@ -0,0 +1,41 @@ +""" +TC: O(ROWS*COLS*4^word length) +SC: O(ROWS*COLS*word length) +""" + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + ROWS = len(board) + COLS = len(board[0]) + path = set() + + def dfs(r,c,i): + if i == len(word): + return True + + if (r < 0 or + c < 0 or + r >= ROWS or + c >= COLS or + word[i] != board[r][c] or + (r,c) in path + ): + return False + + path.add((r,c)) + + res = (dfs(r+1, c, i+1) or + dfs(r, c+1, i+1) or + dfs(r-1, c, i+1) or + dfs(r, c-1, i+1) + ) + path.remove((r,c)) + return res + + for r in range(ROWS): + for c in range(COLS): + if dfs(r,c, 0): return True + + return False + +