Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of word concatenations are there in the list in python
This problem finds how many words in a list are formed by concatenating other words from the same list. We can reuse words multiple times during concatenation.
Given the input words = ["hello", "world", "helloworld", "famous", "worldfamous", "programming"], the output is 2 because "helloworld" is formed by concatenating "hello" + "world", and "worldfamous" is formed by "world" + "famous".
Algorithm
We use a Trie data structure combined with depth-first search (DFS) ?
- Build a Trie: Store all words in a trie for efficient prefix matching
- DFS Search: For each word, check if it can be formed by concatenating other words
- Track Concatenations: Count valid concatenations using a counter
Implementation
class Solution:
def solve(self, words):
# Build trie from all words
trie = {}
for word in words:
layer = trie
for char in word:
if char not in layer:
layer[char] = {}
layer = layer[char]
layer["*"] = () # Mark end of word
def dfs(word, num_concatenated_words):
layer = trie
for i, char in enumerate(word):
# If we found a complete word, try remaining substring
if "*" in layer:
if dfs(word[i:], num_concatenated_words + 1):
return True
# If character not found in trie, this path fails
if char not in layer:
return False
layer = layer[char]
# Check if we reached end of a word and have concatenated at least once
if "*" in layer and num_concatenated_words >= 1:
return True
return False
# Count words that can be formed by concatenation
count = 0
for word in words:
count += dfs(word, 0)
return count
# Test the solution
ob = Solution()
words = ["hello", "world", "helloworld", "famous", "worldfamous", "programming"]
print(ob.solve(words))
The output of the above code is ?
2
How It Works
The trie stores all words with "*" marking word endings. The DFS function checks if a word can be split into valid concatenations ?
- Trie Construction: Each word is inserted character by character
- DFS Exploration: For each character, we check if we can form a valid word boundary
- Recursive Check: When we find a complete word ("*"), we recursively check the remaining substring
- Concatenation Counter: We only count words formed by at least one concatenation
Example Walkthrough
For "helloworld" ?
- Characters 'h','e','l','l','o' form "hello" (found "*" in trie)
- Remaining "world" is checked recursively
- "world" is found as a complete word
- Since
num_concatenated_words ? 1, returnTrue
Conclusion
This solution uses a trie for efficient word lookup and DFS to explore all possible concatenation combinations. The time complexity is O(N*M²) where N is the number of words and M is the average word length.
