Skip to content

Commit 0fe644f

Browse files
authored
Merge pull request #1712 from ivanpenaloza/july27
adding updates
2 parents 195e0ce + 16d3fe0 commit 0fe644f

3 files changed

Lines changed: 165 additions & 41 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
from typing import List, Union, Collection, Mapping, Optional, Dict
2+
3+
class Table:
4+
5+
def __init__(self, name:str, columns: int, rows: Dict, row_count: int = 0):
6+
self.name = name
7+
self.columns = columns
8+
self.rows = rows
9+
self.row_count = row_count
10+
11+
class SQL:
12+
13+
def __init__(self, names: List[str], columns: List[int]):
14+
"""
15+
two string arrays, names and columns, both of size n.
16+
17+
The ith table is represented by the name names[i] and contains columns[i] number of columns
18+
"""
19+
self.names = names
20+
self.columns = columns
21+
self.data = {}
22+
23+
for i in range(0, len(self.names)):
24+
self.data[self.names[i]] = Table(
25+
name = self.names[i],
26+
columns=self.columns[i],
27+
rows={}
28+
)
29+
30+
return
31+
32+
33+
def ins(self, name: str, row: List[str]) -> bool:
34+
"""
35+
Inserts row into the table name and returns true.
36+
If row.length does not match the expected number of columns, or name is not a valid table,
37+
returns false without any insertion.
38+
"""
39+
table: Table = self.data.get(name)
40+
if table is None:
41+
return False
42+
if len(row) != table.columns:
43+
return False
44+
table.row_count += 1
45+
table.rows[table.row_count] = row
46+
47+
return True
48+
49+
50+
def rmv(self, name: str, rowId: int) -> None:
51+
"""
52+
Removes the row rowId from the table name.
53+
If name is not a valid table or there is no row with id rowId, no removal is performed.
54+
"""
55+
table: Table = self.data.get(name, None)
56+
if table is None:
57+
return
58+
59+
if rowId in table.rows:
60+
del table.rows[rowId]
61+
62+
return
63+
64+
65+
def sel(self, name: str, rowId: int, columnId: int) -> str:
66+
"""
67+
Returns the value of the cell at the specified rowId and columnId in the table name.
68+
If name is not a valid table, or the cell (rowId, columnId) is invalid, returns "<null>".
69+
"""
70+
null = "<null>"
71+
table: Table = self.data.get(name, None)
72+
if table is None:
73+
return null
74+
75+
if rowId not in table.rows:
76+
return null
77+
78+
try:
79+
return table.rows[rowId][columnId - 1]
80+
except Exception:
81+
return null
82+
83+
84+
def exp(self, name: str) -> List[str]:
85+
"""
86+
Returns the rows present in the table name.
87+
If name is not a valid table, returns an empty array.
88+
Each row is represented as a string, with each cell value (including the row's id) separated by a ",".
89+
"""
90+
table: Table = self.data.get(name, None)
91+
if table is None:
92+
return []
93+
94+
result = []
95+
96+
for row_id, row in table.rows.items():
97+
row_str = ",".join(row)
98+
result.append(f"{row_id},{row_str}")
99+
100+
return result
101+
102+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
import math
4+
5+
class Solution:
6+
def minimumTime(self, jobs: List[int], workers: List[int]) -> int:
7+
8+
jobs.sort()
9+
workers.sort()
10+
11+
return max([math.ceil((n/d)) for n, d in zip(jobs, workers)])
12+

src/my_project/interviews/google_top_exercises/round_1/25_word_ladder.py

Lines changed: 51 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -3,52 +3,62 @@
33

44

55

6-
76
class Solution:
87
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
9-
"""BFS over a generic-pattern graph.
10-
11-
Build buckets keyed by patterns like 'h*t' so every word that differs
12-
by a single letter shares a bucket. BFS from beginWord finds the
13-
shortest transformation, counting words in the sequence.
148
"""
15-
9+
Find the shortest transformation sequence from beginWord to endWord.
10+
Uses BFS to find the shortest path.
11+
12+
Time Complexity: O(M^2 * N) where M is word length, N is wordList size
13+
Space Complexity: O(M^2 * N) for the pattern dictionary
14+
"""
15+
# If beginWord equals endWord, the sequence is just the word itself
16+
if beginWord == endWord:
17+
return 1
18+
19+
# If endWord is not in wordList, no valid transformation exists
1620
if endWord not in wordList:
1721
return 0
18-
19-
# Map each wildcard pattern -> list of words matching it.
20-
patterns = defaultdict(list)
21-
for word in wordList:
22-
for i in range(len(word)):
23-
pattern = word[:i] + "*" + word[i + 1:]
24-
patterns[pattern].append(word)
25-
26-
# BFS. Level = number of words in the sequence so far (beginWord counts as 1).
27-
queue = deque([(beginWord, 1)])
22+
23+
# Convert wordList to set for O(1) lookup
24+
word_set = set(wordList)
25+
26+
# Build a pattern dictionary to find all words that differ by one letter
27+
# e.g., "hot" -> {"*ot": ["hot"], "h*t": ["hot"], "ho*": ["hot"]}
28+
pattern_dict = defaultdict(list)
29+
word_len = len(beginWord)
30+
31+
# Add beginWord to the set if not present
32+
if beginWord not in word_set:
33+
word_set.add(beginWord)
34+
35+
# Create patterns for all words
36+
for word in word_set:
37+
for i in range(word_len):
38+
pattern = word[:i] + '*' + word[i+1:]
39+
pattern_dict[pattern].append(word)
40+
41+
# BFS to find shortest path
42+
queue = deque([(beginWord, 1)]) # (current_word, level)
2843
visited = {beginWord}
29-
44+
3045
while queue:
31-
word, level = queue.popleft()
32-
33-
if word == endWord:
34-
return level
35-
36-
for i in range(len(word)):
37-
pattern = word[:i] + "*" + word[i + 1:]
38-
for neighbor in patterns[pattern]:
39-
if neighbor not in visited:
40-
visited.add(neighbor)
41-
queue.append((neighbor, level + 1))
42-
print(pattern,visited)
43-
# Clear the bucket so it is not scanned again by another word.
44-
patterns[pattern] = []
45-
46+
current_word, level = queue.popleft()
47+
48+
# Try all possible transformations by replacing each character
49+
for i in range(word_len):
50+
pattern = current_word[:i] + '*' + current_word[i+1:]
51+
52+
# Get all words matching this pattern
53+
for next_word in pattern_dict[pattern]:
54+
if next_word == endWord:
55+
return level + 1
56+
57+
if next_word not in visited:
58+
visited.add(next_word)
59+
queue.append((next_word, level + 1))
60+
61+
# Clear the pattern to avoid revisiting in future iterations
62+
pattern_dict[pattern] = []
63+
4664
return 0
47-
48-
print('hello world')
49-
solution = Solution()
50-
51-
print(solution.ladderLength(beginWord='hat',endWord='hut', wordList=['het',
52-
'hit',
53-
'hot',
54-
'hut']))

0 commit comments

Comments
 (0)