Minimum number of substrings the given string can be splitted into that satisfy the given conditions - GeeksforGeeks

27 May, 2021
Given a string str and a string array arr[], the task is to find the minimum count of substrings this can be split into such that every substring is present in the given string array arr[].
Examples: 
Input: str = “111112”, arr[] = {“11”, “111”, “11111”, “2”}Output: 2 “11111” and “2” are the required substrings. “11”, “111” and “2” can also be a valid answer but it is not the minimum.
Input: str = “123456”, arr[] = {“1”, “12345”, “2345”, “56”, “23”, “456”} Output: 3  
 
Approach: Iterate the string from index 0 and build the prefix string, if the prefix string exists in the given array (a set can be used to check this) then call the function again from the next position in the string and keep track of the overall minimum count of substrings. 
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Set to store all the strings// from the given arrayunordered_set<string> uSet; // To store the required countint minCnt = INT_MAX; // Recursive function to find the count of// substrings that can be splitted starting// from the index start such that all// the substrings are present in the mapvoid findSubStr(string str, int cnt, int start){     // All the chosen substrings    // are present in the map    if (start == str.length()) {         // Update the minimum count        // of substrings        minCnt = min(cnt, minCnt);    }     // Starting from the substrings of length 1    // that start with the given index    for (int len = 1; len <= (str.length() - start); len++) {         // Get the substring        string subStr = str.substr(start, len);         // If the substring is present in the set        if (uSet.find(subStr) != uSet.end()) {             // Recursive call for the            // rest of the string            findSubStr(str, cnt + 1, start + len);        }    }} // Function that inserts all the strings// from the given array in a set and calls// the recursive function to find the// minimum count of substrings str can be// splitted into that satisfy the given conditionvoid findMinSubStr(string arr[], int n, string str){     // Insert all the strings from    // the given array in a set    for (int i = 0; i < n; i++)        uSet.insert(arr[i]);     // Find the required count    findSubStr(str, 0, 0);} // Driver codeint main(){    string str = "123456";    string arr[] = { "1", "12345", "2345",                     "56", "23", "456" };    int n = sizeof(arr) / sizeof(string);     findMinSubStr(arr, n, str);     cout << minCnt;     return 0;}
//Java implementation of above approachimport java.util.*; class GFG{ // Set to store all the Strings// from the given arraystatic Set<String> uSet = new HashSet<String>(); // To store the required countstatic int minCnt = Integer.MAX_VALUE; // Recursive function to find the count of// subStrings that can be splitted starting// from the index start such that all// the subStrings are present in the mapstatic void findSubStr(String str, int cnt, int start){     // All the chosen subStrings    // are present in the map    if (start == str.length())    {         // Update the minimum count        // of subStrings        minCnt = Math.min(cnt, minCnt);    }     // Starting from the subStrings of length 1    // that start with the given index    for (int len = 1;             len <= (str.length() - start); len++)    {         // Get the subString        String subStr = str.substring(start, start + len);         // If the subString is present in the set        if (uSet.contains(subStr))        {             // Recursive call for the            // rest of the String            findSubStr(str, cnt + 1, start + len);        }    }} // Function that inserts all the Strings// from the given array in a set and calls// the recursive function to find the// minimum count of subStrings str can be// splitted into that satisfy the given conditionstatic void findMinSubStr(String arr[],                   int n, String str){     // Insert all the Strings from    // the given array in a set    for (int i = 0; i < n; i++)        uSet.add(arr[i]);     // Find the required count    findSubStr(str, 0, 0);} // Driver codepublic static void main(String args[]){    String str = "123456";    String arr[] = {"1", "12345", "2345",                    "56", "23", "456" };    int n = arr.length;     findMinSubStr(arr, n, str);     System.out.print(minCnt);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approachimport sys # Set to store all the strings# from the given arrayuSet = set(); # To store the required countminCnt = sys.maxsize; # Recursive function to find the count of# substrings that can be splitted starting# from the index start such that all# the substrings are present in the mapdef findSubStr(string, cnt, start) :     global minCnt;         # All the chosen substrings    # are present in the map    if (start == len(string)) :                 # Update the minimum count        # of substrings        minCnt = min(cnt, minCnt);             # Starting from the substrings of length 1    # that start with the given index    for length in range(1, len(string) - start + 1) :                 # Get the substring        subStr = string[start : start + length];                 # If the substring is present in the set        if subStr in uSet :                         # Recursive call for the            # rest of the string            findSubStr(string, cnt + 1, start + length);     # Function that inserts all the strings# from the given array in a set and calls# the recursive function to find the# minimum count of substrings str can be# splitted into that satisfy the given conditiondef findMinSubStr(arr, n, string) :     # Insert all the strings from    # the given array in a set    for i in range(n) :        uSet.add(arr[i]);     # Find the required count    findSubStr(string, 0, 0); # Driver codeif __name__ == "__main__" :     string = "123456";    arr = ["1", "12345", "2345",           "56", "23", "456" ];                         n = len(arr);     findMinSubStr(arr, n, string);     print(minCnt); # This code is contributed by AnkitRai01
// C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ // Set to store all the Strings// from the given arraystatic HashSet<String> uSet = new HashSet<String>(); // To store the required countstatic int minCnt = int.MaxValue; // Recursive function to find the count of// subStrings that can be splitted starting// from the index start such that all// the subStrings are present in the mapstatic void findSubStr(String str, int cnt, int start){     // All the chosen subStrings    // are present in the map    if (start == str.Length)    {         // Update the minimum count        // of subStrings        minCnt = Math.Min(cnt, minCnt);    }     // Starting from the subStrings of length 1    // that start with the given index    for (int len = 1;            len <= (str.Length - start); len++)    {         // Get the subString        String subStr = str.Substring(start, len);         // If the subString is present in the set        if (uSet.Contains(subStr))        {             // Recursive call for the            // rest of the String            findSubStr(str, cnt + 1, start + len);        }    }} // Function that inserts all the Strings// from the given array in a set and calls// the recursive function to find the// minimum count of subStrings str can be// splitted into that satisfy the given conditionstatic void findMinSubStr(String []arr,                          int n, String str){     // Insert all the Strings from    // the given array in a set    for (int i = 0; i < n; i++)        uSet.Add(arr[i]);     // Find the required count    findSubStr(str, 0, 0);} // Driver codepublic static void Main(String []args){    String str = "123456";    String []arr = {"1", "12345", "2345",                    "56", "23", "456" };    int n = arr.Length;     findMinSubStr(arr, n, str);     Console.WriteLine(minCnt);}} // This code is contributed by 29AjayKumar
<script>   // Javascript implementation of the approach // Set to store all the strings// from the given arrayvar uSet = new Set(); // To store the required countvar minCnt = 1000000000; // Recursive function to find the count of// substrings that can be splitted starting// from the index start such that all// the substrings are present in the mapfunction findSubStr( str,  cnt, start){     // All the chosen substrings    // are present in the map    if (start == str.length) {         // Update the minimum count        // of substrings        minCnt = Math.min(cnt, minCnt);    }     // Starting from the substrings of length 1    // that start with the given index    for (var len = 1; len <= (str.length - start); len++) {         // Get the substring        var subStr = str.substring(start, start+len);         // If the substring is present in the set        if (uSet.has(subStr)) {             // Recursive call for the            // rest of the string            findSubStr(str, cnt + 1, start + len);        }    }} // Function that inserts all the strings// from the given array in a set and calls// the recursive function to find the// minimum count of substrings str can be// splitted into that satisfy the given conditionfunction findMinSubStr(arr, n, str){     // Insert all the strings from    // the given array in a set    for (var i = 0; i < n; i++)        uSet.add(arr[i]);     // Find the required count    findSubStr(str, 0, 0);} // Driver code var str = "123456"; var arr = ["1", "12345", "2345",                  "56", "23", "456"]; var n = arr.length; findMinSubStr(arr, n, str); document.write( minCnt);  </script>
3
 
ankthon
andrew1234
29AjayKumar
rutvik_56
prefix
substring
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
Recursive Practice Problems with Solutions
Write a program to reverse digits of a number
Print all possible combinations of r elements in a given array of size n
Recursive Functions
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Python program to check if a string is palindrome or not