Skip to content

Commit

Permalink
[Leo] 9th Week solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
leokim0922 committed Jun 28, 2024
1 parent ab551a4 commit 945d82a
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
48 changes: 48 additions & 0 deletions design-add-and-search-words-data-structure/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class TrieNode:
def __init__(self):
self.links = {}
self.end = False


class WordDictionary:
def __init__(self):
self.root = TrieNode()
self.maxL = 0

def addWord(self, word: str) -> None:
node = self.root
l = 0

for w in word:
if w not in node.links:
node.links[w] = TrieNode()
node = node.links[w]
l += 1

self.maxL = max(self.maxL, l)
node.end = True

## TC: O(len(word)), SC: O(1)

def search(self, word: str) -> bool:
if len(word) > self.maxL:
return False

def helper(index, node):
for inn in range(index, len(word)):
c = word[inn]
if c == ".":
for child in node.links.values():
if helper(inn + 1, child):
return True
return False
else:
if c not in node.links:
return False
node = node.links[c]

return node.end

return helper(0, self.root)

## TC: O(num(node)), SC: O(len(word))
25 changes: 25 additions & 0 deletions number-of-islands/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
res = 0
rows, cols, = len(grid), len(grid[0])

def dfs(x, y):
if x < 0 or y < 0 or x >= rows or y >= cols or grid[x][y] == "0":
return

if grid[x][y] == "1":
grid[x][y] = "0"
dfs(x + 1, y)
dfs(x - 1, y)
dfs(x, y + 1)
dfs(x, y - 1)

for i in range(rows):
for j in range(cols):
if grid[i][j] == "1":
dfs(i, j)
res += 1

return res

## TC & SC: O(m*n)

0 comments on commit 945d82a

Please sign in to comment.