VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-word-combinations/

⇱ CSES Solutions - Word Combinations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Word Combinations

Last Updated : 23 Jul, 2025

You are given a string S of length N and a dictionary arr[] containing K words. In how many ways can you create the string using the words?

Examples:

Input: S = "ababc", K = 4, arr[] = {ab, abab, c, cb}
Output: 2
Explanation: The possible ways are "ab" + "ab" + "c" and "abab" + "c".

Input: S = "geeksforgeeks", K = 3, arr[] = {geeks, for, geeks}
Output: 2
Explanation: The possible ways are "geeks" + "for" + "geeks" and "geeks" + "for" + "geeks" .

Approach: To solve the problem, follow the below idea:

The problem can be solved by Dynamic Programming and Tries. We can maintain a dp[] array such that dp[i] stores the number of ways to form the substring S[i...N-1]. We can travverse the string S from right to left and for every index i, dp[i] is the sum of all dp[j + 1] such that S[i...j] is present in the dictionary. In order to check whether dp[i...j] is present in the dictionary or not, we can insert all the words in a trie and mark the ending of each word with a flag. So, for every index i, we iterate j from i to N-1 and if S[i...j] is present in the dictionary, we add dp[j] to dp[i]. After all the iterations, dp[0] will store the answer.

Step-by-Step algorithm:

  • Declare a dp[] array to store the number of ways to form the string from each index.
  • Declare the Trie data structure to store all the words in a way that allows efficient search and retrieval.
  • Insert each word into the Trie: For each word in the given list, insert it into the Trie using the insertWordInTrie() function. This function iterates over each character in the word, and for each character, it checks if a node already exists in the Trie for this character. If not, it creates a new node. It then marks the last node of each word as the end of a word.
  • For each index i from s.size() - 1 to 0, calculate dp[i] using the countWays() function.
  • The countWays() function iterates over the string from the current index, and for each character, it checks if a node exists in the Trie for this character.
    • If not, it returns the current number of ways.
    • If a node does exist and is marked as end of word then it adds the number of ways to form the string from the next index to the current number of ways.
  • The answer is the number of ways to form the string from index 0, which is stored in dp[0].

Below is the implementation of the algorithm:


Output
2

Time complexity: O(N * N + N * K), where N is the number of length of S and K is the number of words in the dictionary.
Auxiliary Space: O(N * K)

Comment
Article Tags:
Article Tags: