Word formation using concatenation of two dictionary words
Last Updated :
13 Sep, 2023
Given a dictionary find out if given word can be made by two words in the dictionary.
Note: Words in the dictionary must be unique and the word to be formed should not be a repetition of same words that are present in the Trie.
Examples:
Input : dictionary[] = {"news", "abcd", "tree",
"geeks", "paper"}
word = "newspaper"
Output : Yes
We can form "newspaper" using "news" and "paper"
Input : dictionary[] = {"geeks", "code", "xyz",
"forgeeks", "paper"}
word = "geeksforgeeks"
Output : Yes
Input : dictionary[] = {"geek", "code", "xyz",
"forgeeks", "paper"}
word = "geeksforgeeks"
Output : No
The idea is store all words of dictionary in a Trie. We do prefix search for given word. Once we find a prefix, we search for rest of the word.
Algorithm :
1- Store all the words of the dictionary in a Trie.
2- Start searching for the given word in Trie.
If it partially matched then split it into two
parts and then search for the second part in
the Trie.
3- If both found, then return true.
4- Otherwise return false.
Below is the implementation of above idea.
C++
#include<bits/stdc++.h>
using namespace std;
#define char_int(c) ((int)c - (int)'a')
#define SIZE (26)
struct TrieNode
{
TrieNode *children[SIZE];
bool isLeaf;
};
TrieNode *getNode()
{
TrieNode * newNode = new TrieNode;
newNode->isLeaf = false ;
for ( int i =0 ; i< SIZE ; i++)
newNode->children[i] = NULL;
return newNode;
}
void insert(TrieNode *root, string Key)
{
int n = Key.length();
TrieNode * pCrawl = root;
for ( int i=0; i<n; i++)
{
int index = char_int(Key[i]);
if (pCrawl->children[index] == NULL)
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
pCrawl->isLeaf = true ;
}
int findPrefix( struct TrieNode *root, string key)
{
int pos = -1, level;
struct TrieNode *pCrawl = root;
for (level = 0; level < key.length(); level++)
{
int index = char_int(key[level]);
if (pCrawl->isLeaf == true )
pos = level;
if (!pCrawl->children[index])
return pos;
pCrawl = pCrawl->children[index];
}
if (pCrawl != NULL && pCrawl->isLeaf)
return level;
}
bool isPossible( struct TrieNode* root, string word)
{
int len = findPrefix(root, word);
if (len == -1)
return false ;
string split_word(word, len, word.length()-(len));
int split_len = findPrefix(root, split_word);
return (len + split_len == word.length());
}
int main()
{
vector<string> dictionary = { "geeks" , "forgeeks" ,
"quiz" , "geek" };
string word = "geeksquiz" ;
TrieNode *root = getNode();
for ( int i=0; i<dictionary.size(); i++)
insert(root, dictionary[i]);
isPossible(root, word) ? cout << "Yes" :
cout << "No" ;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class GFG {
final static int SIZE = 26 ;
static class TrieNode
{
TrieNode[] children = new TrieNode[SIZE];
boolean isLeaf;
public TrieNode() {
isLeaf = false ;
for ( int i = 0 ; i< SIZE ; i++)
children[i] = null ;
}
}
static TrieNode root;
static void insert(TrieNode root, String Key)
{
int n = Key.length();
TrieNode pCrawl = root;
for ( int i= 0 ; i<n; i++)
{
int index = Key.charAt(i) - 'a' ;
if (pCrawl.children[index] == null )
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
pCrawl.isLeaf = true ;
}
static List<Integer> findPrefix(TrieNode root, String key)
{
List<Integer> prefixPositions = new ArrayList<Integer>();
int level;
TrieNode pCrawl = root;
for (level = 0 ; level < key.length(); level++)
{
int index = key.charAt(level) - 'a' ;
if (pCrawl.isLeaf == true )
prefixPositions.add(level);
if (pCrawl.children[index] == null )
return prefixPositions;
pCrawl = pCrawl.children[index];
}
if (pCrawl != null && pCrawl.isLeaf)
prefixPositions.add(level);
return prefixPositions;
}
static boolean isPossible(TrieNode root, String word)
{
List<Integer> prefixPositions1 = findPrefix(root, word);
if (prefixPositions1.isEmpty())
return false ;
for (Integer len1 : prefixPositions1) {
String restOfSubstring = word.substring(len1, word.length());
List<Integer> prefixPositions2 = findPrefix(root, restOfSubstring);
for (Integer len2 : prefixPositions2) {
if (len1 + len2 == word.length())
return true ;
}
}
return false ;
}
public static void main(String args[])
{
String[] dictionary = { "news" , "newspa" , "paper" , "geek" };
String word = "newspaper" ;
root = new TrieNode();
for ( int i= 0 ; i<dictionary.length; i++)
insert(root, dictionary[i]);
if (isPossible(root, word))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
class TrieNode:
def __init__( self ):
self .children = [ None ] * 26
self .isLeaf = False
def charToInt(ch):
return ord (ch) - ord ( 'a' )
def insert(root, key):
pCrawl = root
for ch in key:
index = charToInt(ch)
if not pCrawl.children[index]:
pCrawl.children[index] = TrieNode()
pCrawl = pCrawl.children[index]
pCrawl.isLeaf = True
def findPrefix(root, key):
pos = - 1
pCrawl = root
for i, ch in enumerate (key):
index = charToInt(ch)
if pCrawl.isLeaf:
pos = i
if not pCrawl.children[index]:
return pos
pCrawl = pCrawl.children[index]
return len (key)
def isPossible(root, word):
len1 = findPrefix(root, word)
if len1 = = - 1 :
return False
split_word = word[len1:]
len2 = findPrefix(root, split_word)
return len1 + len2 = = len (word)
if __name__ = = "__main__" :
dictionary = [ "geeks" , "forgeeks" , "quiz" , "geek" ]
word = "geeksquiz"
root = TrieNode()
for key in dictionary:
insert(root, key)
print ( "Yes" if isPossible(root, word) else "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
readonly public static int SIZE = 26;
public class TrieNode
{
public TrieNode []children = new TrieNode[SIZE];
public bool isLeaf;
public TrieNode()
{
isLeaf = false ;
for ( int i = 0 ; i < SIZE ; i++)
children[i] = null ;
}
}
static TrieNode root;
static void insert(TrieNode root, String Key)
{
int n = Key.Length;
TrieNode pCrawl = root;
for ( int i = 0; i < n; i++)
{
int index = Key[i] - 'a' ;
if (pCrawl.children[index] == null )
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
pCrawl.isLeaf = true ;
}
static List< int > findPrefix(TrieNode root, String key)
{
List< int > prefixPositions = new List< int >();
int level;
TrieNode pCrawl = root;
for (level = 0; level < key.Length; level++)
{
int index = key[level] - 'a' ;
if (pCrawl.isLeaf == true )
prefixPositions.Add(level);
if (pCrawl.children[index] == null )
return prefixPositions;
pCrawl = pCrawl.children[index];
}
if (pCrawl != null && pCrawl.isLeaf)
prefixPositions.Add(level);
return prefixPositions;
}
static bool isPossible(TrieNode root, String word)
{
List< int > prefixPositions1 = findPrefix(root, word);
if (prefixPositions1.Count==0)
return false ;
foreach ( int len1 in prefixPositions1)
{
String restOfSubstring = word.Substring(len1,
word.Length-len1);
List< int > prefixPositions2 = findPrefix(root,
restOfSubstring);
foreach ( int len2 in prefixPositions2)
{
if (len1 + len2 == word.Length)
return true ;
}
}
return false ;
}
public static void Main(String []args)
{
String[] dictionary = { "news" , "newspa" , "paper" , "geek" };
String word = "newspaper" ;
root = new TrieNode();
for ( int i = 0; i < dictionary.Length; i++)
insert(root, dictionary[i]);
if (isPossible(root, word))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
let SIZE = 26;
class TrieNode
{
constructor()
{
this .isLeaf = false ;
this .children = new Array(SIZE);
for (let i = 0 ; i < SIZE; i++)
this .children[i] = null ;
}
}
let root;
function insert(root, Key)
{
let n = Key.length;
let pCrawl = root;
for (let i = 0; i < n; i++)
{
let index = Key[i].charCodeAt(0) -
'a' .charCodeAt(0);
if (pCrawl.children[index] == null )
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
pCrawl.isLeaf = true ;
}
function findPrefix(root, key)
{
let prefixPositions = [];
let level;
let pCrawl = root;
for (level = 0; level < key.length; level++)
{
let index = key[level].charCodeAt(0) -
'a' .charCodeAt(0);
if (pCrawl.isLeaf == true )
prefixPositions.push(level);
if (pCrawl.children[index] == null )
return prefixPositions;
pCrawl = pCrawl.children[index];
}
if (pCrawl != null && pCrawl.isLeaf)
prefixPositions.push(level);
return prefixPositions;
}
function isPossible(root, word)
{
let prefixPositions1 = findPrefix(root, word);
if (prefixPositions1.length == 0)
return false ;
for (let len1 = 0;
len1 < prefixPositions1.length;
len1++)
{
let restOfSubstring = word.substring(
prefixPositions1[len1], word.length);
let prefixPositions2 = findPrefix(
root, restOfSubstring);
for (let len2 = 0;
len2 < prefixPositions2.length;
len2++)
{
if (prefixPositions1[len1] +
prefixPositions2[len2] == word.length)
return true ;
}
}
return false ;
}
let dictionary = [ "news" , "newspa" ,
"paper" , "geek" ];
let word = "newspaper" ;
root = new TrieNode();
for (let i = 0; i < dictionary.length; i++)
insert(root, dictionary[i]);
if (isPossible(root, word))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Exercise :
A generalized version of the problem is to check if a given word can be formed using concatenation of 1 or more dictionary words. Write code for the generalized version.
Time Complexity: The time complexity of the given program is O(MN), where M is the length of the given word and N is the number of words in the dictionary. This is because the program needs to traverse the given word and perform a prefix search in the trie for each substring of the word, which takes O(M) time. Additionally, the program needs to insert all the words in the dictionary into the trie, which takes O(NM) time.
Auxiliary Space: The space complexity of the program is O(NM), where N is the number of words in the dictionary and M is the maximum length of a word in the dictionary. This is because the program needs to store the trie data structure, which requires O(NM) space.
Another Approach
The above approach is implementing the Trie data structure to efficiently store and search the dictionary words. However, we can optimize the code by using the unordered_set data structure instead of Trie. The unordered_set is a hash-based data structure that has an average constant time complexity O(1) for insertion and search operations. Therefore, it can be used to efficiently search for words in the dictionary.
Approach:
- Check if the given word exists in the dictionary. If it does, return true.
- If the given word is not found in the dictionary, then check if it can be formed by concatenating two or more words from the dictionary recursively.
- To check if a word can be formed by concatenating two or more words from the dictionary, the code splits the word into a prefix and a suffix at every possible position and then checks if the prefix exists in the dictionary.
- If the prefix exists in the dictionary, then the suffix is checked recursively to see if it can be formed by concatenating two or more words from the dictionary. This is done by calling the “isPossible” function recursively with the suffix and the dictionary as input.
- If the suffix can be formed by concatenating two or more words from the dictionary, then the entire word can be formed by concatenating the prefix and suffix. In this case, the function returns true.
- If none of the prefixes can be found in the dictionary, or if none of the suffixes can be formed by concatenating two or more words from the dictionary, then the function returns false.
Algorithm:
This code uses recursion to check whether a given word can be formed by concatenating two words from a given dictionary.
- The function “isPossible” takes two parameters: an unordered_set “dict” containing the dictionary of words and a string word to be checked.
- If the word is found in the dictionary, the function returns true. Otherwise, it recursively checks all possible prefixes and suffixes of the word to see if they can be formed by concatenating two words from the “dict”.
- The recursion stops when either the prefix is not found in the dictionary, or the suffix cannot be formed by concatenating two words from the “dict”.
- If the word can be formed by concatenating two words from the “dict”, the function returns true. Otherwise, it returns false.
- The “main” function creates an “unordered_set” of strings containing the dictionary, and then calls the “isPossible” function to check if the given word can be formed by concatenating two words from the dictionary. Finally, it prints “Yes” if the word can be formed, and “No” otherwise.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible(unordered_set<string>& dict, string word)
{
if (dict.find(word) != dict.end())
return true ;
int n = word.length();
for ( int i = 1; i < n; i++) {
string prefix = word.substr(0, i);
string suffix = word.substr(i);
if (dict.find(prefix) != dict.end() && isPossible(dict, suffix))
return true ;
}
return false ;
}
int main()
{
unordered_set<string> dictionary = { "geeks" , "forgeeks" , "quiz" , "geek" };
string word = "geeksquiz" ;
isPossible(dictionary, word) ? cout << "Yes" : cout << "No" ;
return 0;
}
|
Java
import java.util.*;
public class WordFormation {
public static boolean isPossible(Set<String> dict, String word) {
if (dict.contains(word))
return true ;
int n = word.length();
for ( int i = 1 ; i < n; i++) {
String prefix = word.substring( 0 , i);
String suffix = word.substring(i);
if (dict.contains(prefix) && isPossible(dict, suffix))
return true ;
}
return false ;
}
public static void main(String[] args) {
Set<String> dictionary = new HashSet<String>();
dictionary.add( "geeks" );
dictionary.add( "forgeeks" );
dictionary.add( "quiz" );
dictionary.add( "geek" );
String word = "geeksquiz" ;
System.out.println(isPossible(dictionary, word) ? "Yes" : "No" );
}
}
|
Python3
import itertools
def isPossible( dict , word):
if word in dict :
return True
for i in range ( 1 , len (word)):
prefix = word[:i]
suffix = word[i:]
if prefix in dict and isPossible( dict , suffix):
return True
return False
if __name__ = = '__main__' :
dictionary = { 'geeks' , 'forgeeks' , 'quiz' , 'geek' }
word = 'geeksquiz'
if isPossible(dictionary, word):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
public class WordFormation {
public static bool IsPossible(HashSet< string > dict, string word) {
if (dict.Contains(word))
return true ;
int n = word.Length;
for ( int i = 1; i < n; i++) {
string prefix = word.Substring(0, i);
string suffix = word.Substring(i);
if (dict.Contains(prefix) && IsPossible(dict, suffix))
return true ;
}
return false ;
}
public static void Main() {
HashSet< string > dictionary = new HashSet< string >();
dictionary.Add( "geeks" );
dictionary.Add( "forgeeks" );
dictionary.Add( "quiz" );
dictionary.Add( "geek" );
string word = "geeksquiz" ;
Console.WriteLine(IsPossible(dictionary, word) ? "Yes" : "No" );
}
}
|
Javascript
function isPossible(dict, word) {
if (dict.has(word)) {
return true ;
}
let n = word.length;
for (let i = 1; i < n; i++) {
let prefix = word.substring(0, i);
let suffix = word.substring(i);
if (dict.has(prefix) && isPossible(dict, suffix)) {
return true ;
}
}
return false ;
}
let dictionary = new Set([ "geeks" , "forgeeks" , "quiz" , "geek" ]);
let word = "geeksquiz" ;
isPossible(dictionary, word) ? console.log( "Yes" ) : console.log( "No" );
|
Output:
Yes
Time Complexity: The time complexity of the “isPossible” function in this code is O(N^3), where N is the length of the input word. This is because, in the worst case, the function will need to check every possible partition of the word into two parts, which is O(N^2), and for each partition, it may need to recursively check both parts, which can take an additional O(N) time.
Auxiliary Space: The space complexity of this function is also O(N^3) in the worst case, due to the recursion stack. Specifically, in the worst case, the recursion depth will be O(N), and at each level of the recursion, the function may need to store a string of length up to N. Therefore, the overall space complexity is O(N^3).
Share your thoughts in the comments
Please Login to comment...