diff --git a/longest-substring-without-repeating-characters/sun912.py b/longest-substring-without-repeating-characters/sun912.py new file mode 100644 index 000000000..f89727880 --- /dev/null +++ b/longest-substring-without-repeating-characters/sun912.py @@ -0,0 +1,22 @@ +""" + TC: O(n) + SC: O(n) +""" +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + str_list = [] + max_length = 0 + for i in range(len(s)): + if s[i] not in str_list: + str_list.append(s[i]) + else: + if max_length < len(str_list): + max_length = len(str_list) + str_list = str_list[str_list.index(s[i])+1:] + str_list.append(s[i]) + + if max_length < len(str_list): + max_length = len(str_list) + + return max_length + diff --git a/number-of-islands/sun912.py b/number-of-islands/sun912.py new file mode 100644 index 000000000..b36fbe34b --- /dev/null +++ b/number-of-islands/sun912.py @@ -0,0 +1,26 @@ +""" + TC: O(m*n) + SC: O(m*n) +""" +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def dfs(i, j): + if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] == "-1" or grid[i][j] == "0": + return + + grid[i][j] = "-1" + dfs(i+1, j) + dfs(i, j+1) + dfs(i-1, j) + dfs(i, j-1) + + if not grid: + return 0 + + count = 0 + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == "1": + count += 1 + dfs(i, j) + return count diff --git a/reverse-linked-list/sun912.py b/reverse-linked-list/sun912.py new file mode 100644 index 000000000..e28cd18fc --- /dev/null +++ b/reverse-linked-list/sun912.py @@ -0,0 +1,20 @@ +""" + TC: O(n) + SC: O(1) + +""" + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + node, prev = head, None + + while node: + next, node.next = node.next, prev + prev, node = node, next + + return prev