Skip to content

Commit 5f4d683

Browse files
author
Hamid Gasmi
committed
#290 is updated
1 parent 95c9538 commit 5f4d683

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

09-problems/lc_425_word_squares.py

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""
2+
1. Problem Summary / Clarifications / TDD:
3+
4+
2. Intuition:
5+
- All words have the same length => the word square length must have the words length
6+
7+
wall
8+
area
9+
lead
10+
lean
11+
lady
12+
13+
3. Complexity Analysis:
14+
W the size of a word
15+
N the size of the list of words
16+
17+
W^W
18+
19+
20+
"""
21+
22+
class Trie:
23+
def __init__(self, words: List[str]):
24+
self.root = {}
25+
26+
for i in range(len(words)):
27+
self.append(words[i], i)
28+
29+
def append(self, word: str, idx: int):
30+
31+
trie_node = self.root
32+
for c in word:
33+
if c in trie_node:
34+
print(c, idx, trie_node)
35+
trie_node['$'].append(idx)
36+
else:
37+
trie_node[c] = {'$': [idx]}
38+
trie_node = trie_node[c]
39+
40+
def find(self, pattern:[str]) -> List[str]:
41+
42+
node = self.root
43+
for c in pattern:
44+
if c not in node:
45+
return []
46+
node = node[c]
47+
48+
return node['$']
49+
50+
class Solution:
51+
def wordSquares(self, words: List[str]) -> List[List[str]]:
52+
53+
self.square_len = len(words[0])
54+
55+
trie = Trie(words)
56+
#print(trie.root)
57+
#print(trie.find(['b']))
58+
59+
all_words_squares = []
60+
for word in words:
61+
self.find_word_squares(trie, 1, [word], all_words_squares)
62+
63+
return all_words_squares
64+
65+
def find_word_squares(self, trie: Trie, k: int, square: List[str], all_words_squares: List[List[str]]):
66+
if k == self.square_len:
67+
all_words_squares.append(square.copy())
68+
69+
return
70+
71+
prefix = []
72+
for word in square:
73+
prefix.append(word[k])
74+
kth_word_candidates = trie.find(prefix)
75+
76+
for word in kth_word_candidates:
77+
square.append(word)
78+
self.find_word_squares(trie, k + 1, square, all_words_squares)
79+
square.pop()
80+

0 commit comments

Comments
 (0)