Program to count number of word concatenations are there in the list in python


Suppose we have a list of strings; we have to find the number of words that are concatenations of other words also in the list. We can reuse words when concatenating and concatenate any number of times.

So, if the input is like words = ["hello", "world", "helloworld", "famous", "worldfamous", "programming"], then the output will be 2, as "helloworld" is concatenation of "hello" and "world". "worldfamous" is concatenation of "world" and "famous".

To solve this, we will follow these steps:

  • trie := a new map
  • for each word in words, do
    • layer := trie
    • for each w in word, do
      • if w is not in layer, then
        • layer[w] := a new map
      • layer := layer[w]
    • layer["*"] := an empty tuple
    • Define a function dfs() . This will take word, num_concatenated_words
    • layer := trie
    • for each index i and word w in word, do
      • if "*" is in layer, then
        • if dfs(word[from index i to end], num_concatenated_words + 1) is True, then
          • return True
        • if w is not in layer, then
          • return False
      • layer := layer[w]
    • if "*" is in layer and num_concatenated_words >= 1, then
      • return True
    • return False
    • From the main method, do the following:
    • count := 0
    • for each word in words, do
      • count := count + dfs(word, 0)
  • return count

Let us see the following implementation to get better understanding:

Example

Live Demo

class Solution:
   def solve(self, words):
      trie = {}
      for word in words:
         layer = trie
         for w in word:
            if w not in layer:
               layer[w] = {}
            layer = layer[w]
         layer["*"] = ()

      def dfs(word, num_concatenated_words):
         layer = trie

         for i, w in enumerate(word):
            if "*" in layer:
               if dfs(word[i:], num_concatenated_words + 1):
                  return True
            if w not in layer:
               return False
            layer = layer[w]

         if "*" in layer and num_concatenated_words >= 1:
            return True
         return False

      count = 0
     for word in words:
      count += dfs(word, 0)
   return count

ob = Solution()
words = ["hello", "world", "helloworld", "famous", "worldfamous", "programming"]
print(ob.solve(words))

Input

["hello", "world", "helloworld", "famous", "worldfamous", "programming"]

Output

2

Updated on: 26-Nov-2020

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements