Skip to content

Commit 42c41cd

Browse files
authored
Merge pull request #147 from SamTheKorean/solution9
[SAM] Week 9 solutions
2 parents a24465c + 7dd755e commit 42c41cd

File tree

5 files changed

+184
-0
lines changed

5 files changed

+184
-0
lines changed

clone-graph/samthekorean.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# TC : O(n)
2+
# SC : O(n)
3+
class Solution:
4+
def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
5+
if not node:
6+
return None
7+
8+
# Dictionary to store cloned nodes
9+
cloned_nodes = {}
10+
# BFS queue starting with the original node
11+
queue = deque([node])
12+
13+
# Clone the original node
14+
cloned_node = Node(node.val)
15+
cloned_nodes[node] = cloned_node
16+
17+
while queue:
18+
current_node = queue.popleft()
19+
20+
# Iterate through neighbors of the current node
21+
for neighbor in current_node.neighbors:
22+
if neighbor not in cloned_nodes:
23+
# Clone the neighbor and add it to the queue
24+
cloned_neighbor = Node(neighbor.val)
25+
cloned_nodes[neighbor] = cloned_neighbor
26+
queue.append(neighbor)
27+
28+
# Add the cloned neighbor to the cloned current node's neighbors list
29+
cloned_nodes[current_node].neighbors.append(cloned_nodes[neighbor])
30+
31+
return cloned_node

course-schedule/samthekorean.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# V is number of verticles and E is number of edges
2+
# TC : O(V+E)
3+
# SC : O(V+E)
4+
class Solution:
5+
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
6+
7+
pre = defaultdict(list)
8+
9+
for course, p in prerequisites:
10+
pre[course].append(p)
11+
12+
taken = set()
13+
14+
def dfs(course):
15+
if not pre[course]:
16+
return True
17+
18+
if course in taken:
19+
return False
20+
21+
taken.add(course)
22+
23+
for p in pre[course]:
24+
if not dfs(p):
25+
return False
26+
27+
pre[course] = []
28+
return True
29+
30+
for course in range(numCourses):
31+
if not dfs(course):
32+
return False
33+
34+
return True
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# n: number of words | m: length of the word
2+
# TC: O(n*m)
3+
# SC: O(n*m)
4+
5+
6+
class TrieNode:
7+
def __init__(self):
8+
self.children = {} # Dictionary to store child TrieNodes
9+
self.is_word = False # Flag to indicate if a word ends at this node
10+
11+
12+
class WordDictionary:
13+
def __init__(self):
14+
# Initialize WordDictionary with a root TrieNode.
15+
self.root = TrieNode()
16+
17+
def addWord(self, word):
18+
# Add a word to the Trie.
19+
current_node = self.root
20+
21+
# Traverse each character in the word
22+
for character in word:
23+
# Create a new TrieNode if the character doesn't exist in children
24+
current_node = current_node.children.setdefault(character, TrieNode())
25+
26+
# Mark the end of the word at the last character's node
27+
current_node.is_word = True
28+
29+
def search(self, word):
30+
31+
def dfs(node, index):
32+
if index == len(word):
33+
# If reached end of the word, check if current node marks the end of a word
34+
return node.is_word
35+
36+
if word[index] == ".":
37+
# Handle wildcard character '.': Try all possible children
38+
for child in node.children.values():
39+
if dfs(child, index + 1):
40+
return True
41+
elif word[index] in node.children:
42+
# Regular character: Move to the next node
43+
return dfs(node.children[word[index]], index + 1)
44+
45+
# If no match found, return False
46+
return False
47+
48+
# Start DFS from the root of the Trie
49+
return dfs(self.root, 0)

number-of-islands/samthekorean.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# TC : O(n) where n is the number of elements in the two-dimensional list.
2+
# SC : O(n) where n is the depth of the stack of recursive calls.
3+
class Solution:
4+
def numIslands(self, grid: List[List[str]]) -> int:
5+
def dfs(r, c):
6+
# Mark the current cell as visited by setting it to "0"
7+
grid[r][c] = "0"
8+
# Explore all four possible directions (right, down, left, up)
9+
for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
10+
nr, nc = r + dr, c + dc
11+
# Check if the new position is within bounds and is land ("1")
12+
if (
13+
0 <= nr < len(grid)
14+
and 0 <= nc < len(grid[0])
15+
and grid[nr][nc] == "1"
16+
):
17+
dfs(nr, nc)
18+
19+
island_count = 0
20+
# Traverse each cell in the grid
21+
for r in range(len(grid)):
22+
for c in range(len(grid[0])):
23+
if grid[r][c] == "1": # Found an island
24+
island_count += 1 # Increment the island count
25+
dfs(r, c) # Sink the entire island
26+
return island_count # Return the total number of islands
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# m is number of rows and n is number of columns
2+
# TC : O(m*n)
3+
# SC : O(m*n)
4+
class Solution:
5+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
6+
ROWS, COLS = len(heights), len(heights[0])
7+
DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
8+
pacific, atlantic = set(), set()
9+
result: List[List[int]] = []
10+
11+
def dfs(
12+
r: int, c: int, ocean_set: Set[Tuple[int, int]], prev_height: int
13+
) -> None:
14+
if (
15+
r < 0
16+
or r >= ROWS
17+
or c < 0
18+
or c >= COLS
19+
or (r, c) in ocean_set
20+
or heights[r][c] < prev_height
21+
):
22+
return
23+
24+
ocean_set.add((r, c))
25+
26+
for dr, dc in DIRECTIONS:
27+
dfs(r + dr, c + dc, ocean_set, heights[r][c])
28+
29+
# Water Flow Simulation from Pacific (Top and Left borders)
30+
for col in range(COLS):
31+
dfs(0, col, pacific, heights[0][col])
32+
dfs(ROWS - 1, col, atlantic, heights[ROWS - 1][col])
33+
34+
for row in range(ROWS):
35+
dfs(row, 0, pacific, heights[row][0])
36+
dfs(row, COLS - 1, atlantic, heights[row][COLS - 1])
37+
38+
# Finding cells reachable by both Pacific and Atlantic
39+
for r in range(ROWS):
40+
for c in range(COLS):
41+
if (r, c) in pacific and (r, c) in atlantic:
42+
result.append([r, c])
43+
44+
return result

0 commit comments

Comments
 (0)