Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
from typing import List, Union, Collection, Mapping, Optional, Dict

class Table:

def __init__(self, name:str, columns: int, rows: Dict, row_count: int = 0):
self.name = name
self.columns = columns
self.rows = rows
self.row_count = row_count

class SQL:

def __init__(self, names: List[str], columns: List[int]):
"""
two string arrays, names and columns, both of size n.

The ith table is represented by the name names[i] and contains columns[i] number of columns
"""
self.names = names
self.columns = columns
self.data = {}

for i in range(0, len(self.names)):
self.data[self.names[i]] = Table(
name = self.names[i],
columns=self.columns[i],
rows={}
)

return


def ins(self, name: str, row: List[str]) -> bool:
"""
Inserts row into the table name and returns true.
If row.length does not match the expected number of columns, or name is not a valid table,
returns false without any insertion.
"""
table: Table = self.data.get(name)
if table is None:
return False
if len(row) != table.columns:
return False
table.row_count += 1
table.rows[table.row_count] = row

return True


def rmv(self, name: str, rowId: int) -> None:
"""
Removes the row rowId from the table name.
If name is not a valid table or there is no row with id rowId, no removal is performed.
"""
table: Table = self.data.get(name, None)
if table is None:
return

if rowId in table.rows:
del table.rows[rowId]

return


def sel(self, name: str, rowId: int, columnId: int) -> str:
"""
Returns the value of the cell at the specified rowId and columnId in the table name.
If name is not a valid table, or the cell (rowId, columnId) is invalid, returns "<null>".
"""
null = "<null>"
table: Table = self.data.get(name, None)
if table is None:
return null

if rowId not in table.rows:
return null

try:
return table.rows[rowId][columnId - 1]
except Exception:
return null


def exp(self, name: str) -> List[str]:
"""
Returns the rows present in the table name.
If name is not a valid table, returns an empty array.
Each row is represented as a string, with each cell value (including the row's id) separated by a ",".
"""
table: Table = self.data.get(name, None)
if table is None:
return []

result = []

for row_id, row in table.rows.items():
row_str = ",".join(row)
result.append(f"{row_id},{row_str}")

return result


Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
import math

class Solution:
def minimumTime(self, jobs: List[int], workers: List[int]) -> int:

jobs.sort()
workers.sort()

return max([math.ceil((n/d)) for n, d in zip(jobs, workers)])

Original file line number Diff line number Diff line change
Expand Up @@ -3,52 +3,62 @@




class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
"""BFS over a generic-pattern graph.

Build buckets keyed by patterns like 'h*t' so every word that differs
by a single letter shares a bucket. BFS from beginWord finds the
shortest transformation, counting words in the sequence.
"""

Find the shortest transformation sequence from beginWord to endWord.
Uses BFS to find the shortest path.

Time Complexity: O(M^2 * N) where M is word length, N is wordList size
Space Complexity: O(M^2 * N) for the pattern dictionary
"""
# If beginWord equals endWord, the sequence is just the word itself
if beginWord == endWord:
return 1

# If endWord is not in wordList, no valid transformation exists
if endWord not in wordList:
return 0

# Map each wildcard pattern -> list of words matching it.
patterns = defaultdict(list)
for word in wordList:
for i in range(len(word)):
pattern = word[:i] + "*" + word[i + 1:]
patterns[pattern].append(word)

# BFS. Level = number of words in the sequence so far (beginWord counts as 1).
queue = deque([(beginWord, 1)])

# Convert wordList to set for O(1) lookup
word_set = set(wordList)

# Build a pattern dictionary to find all words that differ by one letter
# e.g., "hot" -> {"*ot": ["hot"], "h*t": ["hot"], "ho*": ["hot"]}
pattern_dict = defaultdict(list)
word_len = len(beginWord)

# Add beginWord to the set if not present
if beginWord not in word_set:
word_set.add(beginWord)

# Create patterns for all words
for word in word_set:
for i in range(word_len):
pattern = word[:i] + '*' + word[i+1:]
pattern_dict[pattern].append(word)

# BFS to find shortest path
queue = deque([(beginWord, 1)]) # (current_word, level)
visited = {beginWord}

while queue:
word, level = queue.popleft()

if word == endWord:
return level

for i in range(len(word)):
pattern = word[:i] + "*" + word[i + 1:]
for neighbor in patterns[pattern]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, level + 1))
print(pattern,visited)
# Clear the bucket so it is not scanned again by another word.
patterns[pattern] = []

current_word, level = queue.popleft()

# Try all possible transformations by replacing each character
for i in range(word_len):
pattern = current_word[:i] + '*' + current_word[i+1:]

# Get all words matching this pattern
for next_word in pattern_dict[pattern]:
if next_word == endWord:
return level + 1

if next_word not in visited:
visited.add(next_word)
queue.append((next_word, level + 1))

# Clear the pattern to avoid revisiting in future iterations
pattern_dict[pattern] = []

return 0

print('hello world')
solution = Solution()

print(solution.ladderLength(beginWord='hat',endWord='hut', wordList=['het',
'hit',
'hot',
'hut']))
Loading