diff --git a/clone-graph/imgolden77.py b/clone-graph/imgolden77.py new file mode 100644 index 0000000000..9c506de4cb --- /dev/null +++ b/clone-graph/imgolden77.py @@ -0,0 +1,33 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val = 0, neighbors = None): + self.val = val + self.neighbors = neighbors if neighbors is not None else [] +""" + +from typing import Optional +class Solution: + def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: + if not node: + return None + old_to_new = {} + + def dfs(curr_node): + if curr_node in old_to_new: + return old_to_new[curr_node] + + copy = Node(curr_node.val) + old_to_new[curr_node] = copy + + for neighbors in curr_node.neighbors: + copy.neighbors.append(dfs(neighbors)) + + return copy + + return dfs(node) + + # O(N+E) time complexity where N is the number of nodes and E is the number of edges in the graph. + # O(N) space complexity for the hashmap and the recursion stack in the worst case. + + \ No newline at end of file diff --git a/longest-repeating-character-replacement/imgolden77.py b/longest-repeating-character-replacement/imgolden77.py new file mode 100644 index 0000000000..65b7a615d9 --- /dev/null +++ b/longest-repeating-character-replacement/imgolden77.py @@ -0,0 +1,28 @@ +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + start = 0 + max_len = 0 + seen = {} + + for i, char in enumerate(s): + + seen[char] = seen.get(char, 0) + 1 + # what I wrote initially: + # if char not in seen: + # seen[char] = 1 + # else: + # seen[char] += 1 + max_val = max(list(seen.values())) + window_len = i - start + 1 + if window_len - max_val <= k: + max_len = max(max_len, window_len) + else: + seen[s[start]] -= 1 + start += 1 + + return max_len + + # O(N) time complexity and O(1) space complexity. + + + \ No newline at end of file diff --git a/longest-substring-without-repeating-characters/imgolden77.py b/longest-substring-without-repeating-characters/imgolden77.py new file mode 100644 index 0000000000..fd145d2a11 --- /dev/null +++ b/longest-substring-without-repeating-characters/imgolden77.py @@ -0,0 +1,32 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + h = [] + max_s = 0 + for i in s: + if i not in h: + h.append(i) + else: + h=h[h.index(i)+1:] + h.append(i) + #I reset h=[] but it had problemswith the cases like "dvdf" + #So I modified it to h=h[h.index(i)+1:] + max_s = max(max_s, len(h)) + + return max_s + +#O(N^2) time complexity due to "if i not in h" and O(min(m,n)) space complexity where m is the size of the charset and n is the size of the string s. + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + seen = {} + start = 0 + max_len = 0 + for i, char in enumerate(s): + if char in seen and seen[char]>=start: + start= seen[char]+1 + seen[char]=i + max_len = max(max_len, i - start +1) + + return max_len +#O(N) time complexity and O(min(m,n)) space complexity where m is the size of the charset and n is the size of the string s. +#Dictionary search and insert operations are O(1) on average. so it is O(N) overall. \ No newline at end of file diff --git a/number-of-islands/imgolden77.py b/number-of-islands/imgolden77.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/palindromic-substrings/imgolden77.py b/palindromic-substrings/imgolden77.py new file mode 100644 index 0000000000..c169fa7ace --- /dev/null +++ b/palindromic-substrings/imgolden77.py @@ -0,0 +1,25 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + total_count = 0 + + def expand(left, right): + local_count = 0 + while left>=0 and right< len(s) and s[left] == s[right]: + # while s[left] == s[right] and left>=0 and right< len(s) : + # The above line would cause index error if left or right go out of bounds + local_count += 1 + left -= 1 + right += 1 + return local_count + + for i in range(len(s)): + total_count += expand(i, i) + total_count += expand(i, i+1) + + return total_count + +#Complexity Analysis +#Time complexity: O(n^2) where n is the length of the input string s. +#Space complexity: O(1) as we are using only a constant amount of extra space +# Manacher's Algorithm can achieve O(n) time complexity for this problem. + diff --git a/reverse-bits/imgolden77.py b/reverse-bits/imgolden77.py new file mode 100644 index 0000000000..e897d95634 --- /dev/null +++ b/reverse-bits/imgolden77.py @@ -0,0 +1,16 @@ +class Solution: + def reverseBits(self, n: int) -> int: + if n == 0: + return 0 + res = 0 + for i in range(32): + bit = n & 1 + res = res + bit + res = res << 1 + n = n >> 1 + res = res >> 1 + + return res + +# Complexity O(1) - Time: 32 iterations, Space: O(1) no extra space used + diff --git a/reverse-linked-list/imgolden77.py b/reverse-linked-list/imgolden77.py new file mode 100644 index 0000000000..4a32522286 --- /dev/null +++ b/reverse-linked-list/imgolden77.py @@ -0,0 +1,20 @@ +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + curr = head + prev = None + + while curr is not None: # once was "while curr.next is not None:" but that showed AttributeError: 'NoneType' object has no attribute 'next' + if prev: + post = curr.next + curr.next = prev + prev = curr + curr = post + else: + post = curr.next + prev = curr + curr.next = None + curr = post + + return prev + +# First time, return Curr, but the result was [] so I changed to "return prev" as the new head of the reversed Linked list. \ No newline at end of file diff --git a/valid-parentheses/imgolden77.py b/valid-parentheses/imgolden77.py new file mode 100644 index 0000000000..76e4aa4045 --- /dev/null +++ b/valid-parentheses/imgolden77.py @@ -0,0 +1,57 @@ +# First try O(n) time complexity +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + former= ['(', '{', '['] + + for i in s: + if i in former: + stack.append(i) + elif i == ')': + if stack== []: + return False + elif stack[-1]== '(': + stack.pop() + else: + return False + elif i == '}': + if stack== []: + return False + elif stack[-1]== '{': + stack.pop() + else: + return False + elif i == ']': + if stack == []: + return False + elif stack[-1]== '[': + stack.pop() + else: + return False + + + if stack == []: + return True + else: + return False + +# Second try: O(n) time complexity +# refer other people's code +# 'not stack' is more pythonic way to check empty stack +# par_map dictionary to map closing to opening parentheses +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + par_map = {')':'(', '}':'{', ']':'['} + + for i in s: + if i in par_map.values(): + stack.append(i) + elif i in par_map: + if not stack or stack[-1] !=par_map[i]: + return False + stack.pop() + else: + return False + + return not stack \ No newline at end of file