diff --git a/src/my_project/interviews/amazon_high_frequency_23/common_algos/number_of_islands_round_4.py b/src/my_project/interviews/amazon_high_frequency_23/common_algos/number_of_islands_round_4.py new file mode 100644 index 00000000..7da76e82 --- /dev/null +++ b/src/my_project/interviews/amazon_high_frequency_23/common_algos/number_of_islands_round_4.py @@ -0,0 +1,39 @@ +from typing import List, Union, Collection, Mapping, Optional +from collections import deque + +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + """BFS approach - explores island level by level""" + + if not grid: + return 0 + + rows, cols = len(grid), len(grid[0]) + islands = 0 + + def bfs(r: int, c: int): + queue = deque([(r,c)]) + grid[r][c] = '0' + + while queue: + row, col = queue.popleft() + + for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]: + nr, nc = row + dr, col + dc + if (0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1'): + grid[nr][nc] = '0' + queue.append((nr, nc)) + + for r in range(rows): + for c in range(cols): + if grid[r][c] == '1': + islands += 1 + bfs(r,c) + + return islands + + + def numIslands_DFS(grid: List[List[str]]) -> int: + """DFS approach - explores island depth-first""" + + pass \ No newline at end of file diff --git a/src/my_project/interviews/amazon_high_frequency_23/common_algos/two_sum_round_4.py b/src/my_project/interviews/amazon_high_frequency_23/common_algos/two_sum_round_4.py new file mode 100644 index 00000000..e03fe46f --- /dev/null +++ b/src/my_project/interviews/amazon_high_frequency_23/common_algos/two_sum_round_4.py @@ -0,0 +1,16 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + + answer = dict() + + for k, v in enumerate(nums): + + if v in answer: + return [answer[v], k] + else: + answer[target - v] = k + + return [] \ No newline at end of file diff --git a/src/my_project/interviews/amazon_high_frequency_23/common_algos/valid_palindrome_round_4.py b/src/my_project/interviews/amazon_high_frequency_23/common_algos/valid_palindrome_round_4.py new file mode 100644 index 00000000..cad2b1e6 --- /dev/null +++ b/src/my_project/interviews/amazon_high_frequency_23/common_algos/valid_palindrome_round_4.py @@ -0,0 +1,22 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod +import re + +class Solution: + def isPalindrome(self, s: str) -> bool: + + # To lowercase + s = s.lower() + + # Remove non-alphanumeric characters + s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s) + + # Determine if s is palindrome or not + len_s = len(s) + + for i in range(len_s//2): + + if s[i] != s[len_s - 1 - i]: + return False + + return True \ No newline at end of file