Skip to content

Commit e02a483

Browse files
committed
Added #246
1 parent 40ae619 commit e02a483

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Diff for: challenges/chain-words.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
#246
3+
Dropbox
4+
5+
Given a list of words, determine whether the words can be chained to form a circle.
6+
A word X can be placed in front of another word Y in a circle if the last character of X is same as the first character of Y.
7+
8+
For example, the words ['chair', 'height', 'racket', 'touch', 'tunic'] can form the following circle:
9+
chair --> racket --> touch --> height --> tunic --> chair.
10+
11+
"""
12+
13+
def checkForCycleHelper(usedWords, remainingWords):
14+
if len(remainingWords) == 0:
15+
# print(usedWords, end=" ") # Uncomment to see the chain
16+
return True
17+
18+
lastLetter = usedWords[-1][-1]
19+
for i in range(len(remainingWords)):
20+
nextWord = remainingWords[i]
21+
if nextWord.startswith(lastLetter) and checkForCycleHelper(usedWords+[nextWord], remainingWords[:i]+remainingWords[i+1:]):
22+
return True
23+
24+
return False
25+
26+
27+
def checkForCycle(words):
28+
return checkForCycleHelper([words[0]], words[1:])
29+
30+
def main():
31+
print(checkForCycle(["geek", "king"])) # True ['geek', 'king']
32+
print(checkForCycle(["for", "geek", "rig", "kaf"])) # True ['for', 'rig', 'geek', 'kaf']
33+
print(checkForCycle(["aab", "bac", "aaa", "cda"])) # True ['aab', 'bac', 'cda', 'aaa']
34+
print(checkForCycle(["aaa", "bbb", "baa", "aab"])) # True ['aaa', 'aab', 'bbb', 'baa']
35+
print(checkForCycle(["aaa"])) # True ['aaa']
36+
print(checkForCycle(["aaa", "bbb"])) # False
37+
print(checkForCycle(["abc", "efg", "cde", "ghi", "ija"])) # True ['abc', 'cde', 'efg', 'ghi', 'ija']
38+
print(checkForCycle(["ijk", "kji", "abc", "cba"])) # False
39+
40+
41+
if __name__ == "__main__":
42+
main()

Diff for: index.md

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
* [#215 Bottom View Of Binary Tree](./challenges/bottom-view-of-binary-tree.py)
5656
* [#222 Standardize Absolute Path](./challenges/standardize-absolute-path.py)
5757
* [#244 Sieve Of Eratosthenes - Prime Generator](./challenges/sieve-of-eratosthenes-prime-generator.py)
58+
* [#246 Chain Words](./challenges/chain-words.py)
5859

5960
## Lessons
6061

0 commit comments

Comments
 (0)