Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e76bd94

Browse files
Add easy and hard problems
1 parent 2a6e17f commit e76bd94

File tree

2 files changed

+206
-0
lines changed

2 files changed

+206
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
# LONGEST WORD IN DICTIONARY
3+
4+
Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
5+
6+
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
7+
8+
9+
10+
Example 1:
11+
12+
Input: words = ["w","wo","wor","worl","world"]
13+
Output: "world"
14+
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
15+
Example 2:
16+
17+
Input: words = ["a","banana","app","appl","ap","apply","apple"]
18+
Output: "apple"
19+
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
20+
21+
22+
Constraints:
23+
24+
1 <= words.length <= 1000
25+
1 <= words[i].length <= 30
26+
words[i] consists of lowercase English letters.
27+
"""
28+
29+
from typing import List
30+
31+
class Solution:
32+
def longestWord(self, words: List[str]) -> str:
33+
words.sort(key = lambda x: (len(x), x))
34+
trie = Trie()
35+
longestWord = (None, 0)
36+
for word in words:
37+
flag = trie.insert(word)
38+
if flag and len(word) > longestWord[1]:
39+
longestWord = (word, len(word))
40+
41+
return longestWord[0] if longestWord[0] is not None else ""
42+
43+
class Trie:
44+
def __init__(self):
45+
self.root = {}
46+
self.endSymbol = "*"
47+
self.root[self.endSymbol] = True
48+
49+
def insert(self, word):
50+
current = self.root
51+
flag = True
52+
for letter in word:
53+
if self.endSymbol not in current:
54+
flag = False
55+
if letter not in current:
56+
current[letter] = {}
57+
current = current[letter]
58+
current[self.endSymbol] = True
59+
return flag
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
"""
2+
# PREFIX AND SUFFIX SEARCH
3+
4+
Design a special dictionary with some words that searchs the words in it by a prefix and a suffix.
5+
6+
Implement the WordFilter class:
7+
8+
WordFilter(string[] words) Initializes the object with the words in the dictionary.
9+
f(string prefix, string suffix) Returns the index of the word in the dictionary, which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.
10+
11+
12+
Example 1:
13+
14+
Input
15+
["WordFilter", "f"]
16+
[[["apple"]], ["a", "e"]]
17+
Output
18+
[null, 0]
19+
20+
Explanation
21+
WordFilter wordFilter = new WordFilter(["apple"]);
22+
wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = 'e".
23+
24+
25+
Constraints:
26+
27+
1 <= words.length <= 15000
28+
1 <= words[i].length <= 10
29+
1 <= prefix.length, suffix.length <= 10
30+
words[i], prefix and suffix consist of lower-case English letters only.
31+
At most 15000 calls will be made to the function f.
32+
"""
33+
34+
# THIS SOLUTION WILL RESULT IN TIME LIMIT EXCEEDED ERROR.
35+
36+
from typing import Collection, List
37+
38+
class WordFilter:
39+
40+
def __init__(self, words: List[str]):
41+
self.root = {}
42+
self.endSymbol = "*"
43+
self.suffixIndex = "SuffixIndexes"
44+
self.prefixIndex = "PrefixIndexes"
45+
for index, word in enumerate(words):
46+
self.populateTrie(word, index)
47+
48+
def populateTrie(self, word, index):
49+
for i in range(len(word)):
50+
current = self.root
51+
52+
for j in range(i, len(word)):
53+
letter = word[j]
54+
if letter not in current:
55+
current[letter] = {}
56+
current = current[letter]
57+
if self.endSymbol in current and self.suffixIndex in current:
58+
current[self.suffixIndex].append(index)
59+
else:
60+
current[self.endSymbol] = True
61+
current[self.suffixIndex] = [index]
62+
63+
for i in range(len(word)):
64+
current = self.root
65+
66+
for j in range(i + 1):
67+
letter = word[j]
68+
if letter not in current:
69+
current[letter] = {}
70+
current = current[letter]
71+
if self.endSymbol in current and self.prefixIndex in current:
72+
current[self.prefixIndex].append(index)
73+
else:
74+
current[self.endSymbol] = True
75+
current[self.prefixIndex] = [index]
76+
77+
78+
def f(self, prefix: str, suffix: str) -> int:
79+
prefixIndexes = self.searchPrefixIndexes(prefix)
80+
suffixIndexes = self.searchSuffixIndexes(suffix)
81+
if prefixIndexes == -1 or suffixIndexes == -1:
82+
return -1
83+
84+
prefixIndexes.sort(reverse=True)
85+
suffixIndexes.sort(reverse=True)
86+
i, j = 0, 0
87+
while i < len(prefixIndexes) and j < len(suffixIndexes):
88+
if prefixIndexes[i] == suffixIndexes[j]:
89+
return prefixIndexes[i]
90+
elif prefixIndexes[i] > suffixIndexes[j]:
91+
i += 1
92+
else:
93+
j += 1
94+
95+
return -1
96+
97+
def searchPrefixIndexes(self, prefix):
98+
current = self.root
99+
for letter in prefix:
100+
if letter not in current:
101+
return -1
102+
current = current[letter]
103+
if self.endSymbol in current:
104+
return current[self.prefixIndex]
105+
106+
def searchSuffixIndexes(self, suffix):
107+
current = self.root
108+
for letter in suffix:
109+
if letter not in current:
110+
return -1
111+
current = current[letter]
112+
if self.endSymbol in current:
113+
return current[self.suffixIndex]
114+
115+
116+
117+
# Your WordFilter object will be instantiated and called as such:
118+
# obj = WordFilter(words)
119+
# param_1 = obj.f(prefix,suffix)
120+
121+
########################################
122+
# THIS IS THE MOST EFFICIENT SOLUTION
123+
########################################
124+
125+
Trie = lambda: Collection.defaultdict(Trie)
126+
WEIGHT = False
127+
128+
class WordFilter(object):
129+
def __init__(self, words):
130+
self.trie = Trie()
131+
132+
for weight, word in enumerate(words):
133+
word += '#'
134+
for i in range(len(word)):
135+
cur = self.trie
136+
cur[WEIGHT] = weight
137+
for j in range(i, 2 * len(word) - 1):
138+
cur = cur[word[j % len(word)]]
139+
cur[WEIGHT] = weight
140+
141+
def f(self, prefix, suffix):
142+
cur = self.trie
143+
for letter in suffix + '#' + prefix:
144+
if letter not in cur:
145+
return -1
146+
cur = cur[letter]
147+
return cur[WEIGHT]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /