Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Minimize length of Substrings containing at least one common Character
Next article icon

Minimize length of prefix of string S containing all characters of another string T

Last Updated : 08 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two string S and T, the task is to find the minimum length prefix from S which consists of all characters of string T. If S does not contain all characters of string T, print -1.

Examples: 

Input: S = “MarvoloGaunt”, T = “Tom” 
Output: 12 
Explanation: 
The 12 length prefix “MarvoloGaunt” contains all the characters of “Tom”

Input: S = “TheWorld”, T = “Dio” 
Output: -1 
Explanation: 
The string “TheWorld” does not contain the character ‘i’ from the string “Dio”. 

Naive Approach: 
The simplest approach to solve the problem is to iterate the string S and compare the frequency of each letter in both the prefix and T and return the length traversed if the required prefix is found. Otherwise, return -1. 

Time Complexity: O(N2) 
Auxiliary Space: O(1)

Efficient Approach: 
To optimize the above approach, follow the steps below: 

  1. Store the frequencies of T in a dictionary dictCount.
  2. Store the number of unique letters with a count greater than 0 as nUnique.
  3. Iterate over [0, N], and obtain the ith index character of S as ch.
  4. Decrease the count of ch from dictCount if it exists. If this count goes to 0, decrease nUnique by 1.
  5. If nUnique reaches 0, return the length traversed till then.
  6. After complete traversal of S, if nUnique still exceeds 0, print -1.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
int getPrefixLength(string srcStr,
                    string targetStr)
{
     
    // Base Case - if T is empty,
    // it matches 0 length prefix
    if (targetStr.length() == 0)
        return 0;
   
    // Convert strings to lower
    // case for uniformity
    transform(srcStr.begin(),
              srcStr.end(),
              srcStr.begin(), ::tolower);
    transform(targetStr.begin(),
              targetStr.end(),
              targetStr.begin(), ::tolower);
   
    map<char, int> dictCount;
    int nUnique = 0;
   
    // Update dictCount to the
    // letter count of T
    for(char ch: targetStr)
    {
         
        // If new character is found,
        // initialize its entry,
        // and increase nUnique
        if (dictCount.find(ch) ==
            dictCount.end())
        {
            nUnique += 1;
            dictCount[ch] = 0;
        }
   
        // Increase count of ch
        dictCount[ch] += 1;
    }
   
    // Iterate from 0 to N
    for(int i = 0; i < srcStr.length(); i++)
    {
         
        // i-th character
        char ch = srcStr[i];
   
        // Skip if ch not in targetStr
        if (dictCount.find(ch) ==
            dictCount.end())
            continue;
             
        // Decrease Count
        dictCount[ch] -= 1;
   
        // If the count of ch reaches 0,
        // we do not need more ch,
        // and can decrease nUnique
        if (dictCount[ch] == 0)
            nUnique -= 1;
   
        // If nUnique reaches 0,
        // we have found required prefix
        if (nUnique == 0)
            return (i + 1);
    }
   
    // Otherwise
    return -1;
}
 
// Driver code  
int main()
{
    string S = "MarvoloGaunt";
    string T = "Tom";
   
    cout << getPrefixLength(S, T);
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07
 
 

Java




// Java program for the above approach
import java.util.*;
public class Main
{
    public static int getPrefixLength(String srcStr, String targetStr)
    {
       
        // Base Case - if T is empty,
        // it matches 0 length prefix
        if (targetStr.length() == 0)
            return 0;
              
        // Convert strings to lower
        // case for uniformity
        srcStr = srcStr.toLowerCase();
        targetStr = targetStr.toLowerCase();
          
        HashMap<Character, Integer> dictCount = new HashMap<>();
                                                     
        int nUnique = 0;
        
        // Update dictCount to the
        // letter count of T
        for(char ch : targetStr.toCharArray())
        {
              
            // If new character is found,
            // initialize its entry,
            // and increase nUnique
            if (dictCount.containsKey(ch) != true)
            {
                nUnique += 1;
                dictCount.put(ch, 0);
            }
              
            // Increase count of ch
            dictCount.replace(ch, dictCount.get(ch) + 1);
        }
        
        // Iterate from 0 to N
        for(int i = 0; i < srcStr.length(); i++)
        {
              
            // i-th character
            char ch = srcStr.charAt(i);
        
            // Skip if ch not in targetStr
            if (dictCount.containsKey(ch) != true)
                continue;
                  
            // Decrease Count
            dictCount.replace(ch, dictCount.get(ch) - 1);
        
            // If the count of ch reaches 0,
            // we do not need more ch,
            // and can decrease nUnique
            if (dictCount.get(ch) == 0)
                nUnique -= 1;
        
            // If nUnique reaches 0,
            // we have found required prefix
            if (nUnique == 0)
                return (i + 1);
        }
        
        // Otherwise
        return -1;
    }
   
    // Driver code
    public static void main(String[] args) {
        String S = "MarvoloGaunt";
        String T = "Tom";
        
        System.out.println(getPrefixLength(S, T));
    }
}
 
// This code is contributed by divyesh072019
 
 

Python3




# Python3 program for the above approach
 
def getPrefixLength(srcStr, targetStr):
 
    # Base Case - if T is empty,
    # it matches 0 length prefix
    if(len(targetStr) == 0):
        return 0
 
    # Convert strings to lower
    # case for uniformity
    srcStr = srcStr.lower()
    targetStr = targetStr.lower()
 
    dictCount = dict([])
    nUnique = 0
 
    # Update dictCount to the
    # letter count of T
    for ch in targetStr:
 
        # If new character is found,
        # initialize its entry,
        # and increase nUnique
        if(ch not in dictCount):
            nUnique += 1
            dictCount[ch] = 0
 
        # Increase count of ch
        dictCount[ch] += 1
 
    # Iterate from 0 to N
    for i in range(len(srcStr)):
 
        # i-th character
        ch = srcStr[i]
 
        # Skip if ch not in targetStr
        if(ch not in dictCount):
            continue
        # Decrease Count
        dictCount[ch] -= 1
 
        # If the count of ch reaches 0,
        # we do not need more ch,
        # and can decrease nUnique
        if(dictCount[ch] == 0):
            nUnique -= 1
 
        # If nUnique reaches 0,
        # we have found required prefix
        if(nUnique == 0):
            return (i + 1)
 
    # Otherwise
    return -1
 
 
# Driver Code
if __name__ == "__main__":
 
    S = "MarvoloGaunt"
    T = "Tom"
 
    print(getPrefixLength(S, T))
 
 

C#




// C# program for the above approach
using System.Collections.Generic;
using System;
 
class GFG{
 
static int getPrefixLength(string srcStr,
                           string targetStr)
{
     
    // Base Case - if T is empty,
    // it matches 0 length prefix
    if (targetStr.Length == 0)
        return 0;
         
    // Convert strings to lower
    // case for uniformity
    srcStr = srcStr.ToLower();
    targetStr = targetStr.ToLower();
     
    Dictionary<char,
               int> dictCount = new Dictionary<char,
                                               int>();
                                                
    int nUnique = 0;
   
    // Update dictCount to the
    // letter count of T
    foreach(var ch in targetStr)
    {
         
        // If new character is found,
        // initialize its entry,
        // and increase nUnique
        if (dictCount.ContainsKey(ch) != true)
        {
            nUnique += 1;
            dictCount[ch] = 0;
        }
         
        // Increase count of ch
        dictCount[ch] += 1;
    }
   
    // Iterate from 0 to N
    for(int i = 0; i < srcStr.Length; i++)
    {
         
        // i-th character
        char ch = srcStr[i];
   
        // Skip if ch not in targetStr
        if (dictCount.ContainsKey(ch) != true)
            continue;
             
        // Decrease Count
        dictCount[ch] -= 1;
   
        // If the count of ch reaches 0,
        // we do not need more ch,
        // and can decrease nUnique
        if (dictCount[ch] == 0)
            nUnique -= 1;
   
        // If nUnique reaches 0,
        // we have found required prefix
        if (nUnique == 0)
            return (i + 1);
    }
   
    // Otherwise
    return -1;
}
 
// Driver code  
public static void Main()
{
    string S = "MarvoloGaunt";
    string T = "Tom";
   
    Console.Write(getPrefixLength(S, T));
}
}
 
// This code is contributed by Stream_Cipher
 
 

Javascript




<script>
      // JavaScript program for the above approach
      function getPrefixLength(srcStr, targetStr) {
        // Base Case - if T is empty,
        // it matches 0 length prefix
        if (targetStr.length === 0) return 0;
 
        // Convert strings to lower
        // case for uniformity
        srcStr = srcStr.toLowerCase();
        targetStr = targetStr.toLowerCase();
 
        var dictCount = {};
 
        var nUnique = 0;
 
        // Update dictCount to the
        // letter count of T
        for (const ch of targetStr) {
          // If new character is found,
          // initialize its entry,
          // and increase nUnique
          if (dictCount.hasOwnProperty(ch) !== true) {
            nUnique += 1;
            dictCount[ch] = 0;
          }
 
          // Increase count of ch
          dictCount[ch] += 1;
        }
 
        // Iterate from 0 to N
        for (var i = 0; i < srcStr.length; i++) {
          // i-th character
          var ch = srcStr[i];
 
          // Skip if ch not in targetStr
          if (dictCount.hasOwnProperty(ch) !== true) continue;
 
          // Decrease Count
          dictCount[ch] -= 1;
 
          // If the count of ch reaches 0,
          // we do not need more ch,
          // and can decrease nUnique
          if (dictCount[ch] === 0) nUnique -= 1;
 
          // If nUnique reaches 0,
          // we have found required prefix
          if (nUnique === 0) return i + 1;
        }
 
        // Otherwise
        return -1;
      }
 
      // Driver code
      var S = "MarvoloGaunt";
      var T = "Tom";
 
      document.write(getPrefixLength(S, T));
    </script>
 
 

 
 

Output: 
12

 

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 

 



Next Article
Minimize length of Substrings containing at least one common Character

J

joshi_arihant
Improve
Article Tags :
  • DSA
  • Hash
  • Searching
  • Strings
  • frequency-counting
  • prefix
  • subsequence
Practice Tags :
  • Hash
  • Searching
  • Strings

Similar Reads

  • Minimize length of a string by removing suffixes and prefixes of same characters
    Given a string S of length N consisting only of characters 'a', 'b', and 'c', the task is to minimize the length of the given string by performing the following operations only once: Divide the string into two non-empty substrings and then, append the left substring to the end of the right substring
    6 min read
  • Minimize length of Substrings containing at least one common Character
    Given a string str, the task is to find the minimum length of substrings such that all the sub strings of that length from str contains at least one common character. If no such length can be obtained, print -1. Example: Input: str = "saad" Output: 2 Explanation: All the substrings of length two of
    10 min read
  • Minimize length of a string by removing occurrences of another string from it as a substring
    Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S
    8 min read
  • Smallest window in a String containing all characters of other String
    Given two strings s (length m) and p (length n), the task is to find the smallest substring in s that contains all characters of p, including duplicates. If no such substring exists, return "-1". If multiple substrings of the same length are found, return the one with the smallest starting index. Ex
    15+ min read
  • Minimize operations to make one string contain only characters from other string
    Given two strings S1 and S2 containing only lower case English alphabets, the task is to minimize the number of operations required to make S1 contain only characters from S2 where in each operation any character of S1 can be converted to any other letter and the cost of the operation will be differ
    9 min read
  • Smallest string containing all unique characters from given array of strings
    Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are u
    9 min read
  • Count of substrings of a string containing another given string as a substring
    Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = “dab”S[1, 2] = “ab”S[1, 3] = “abc”S[0, 3] = “dabc” Input: S
    8 min read
  • Minimize the count of characters to be added or removed to make String repetition of same substring
    Given a string S consisting of N characters, the task is to modify the string S by performing the minimum number of following operations such that the modified string S is the concatenation of its half. Insert any new character at any index in the string.Remove any character from the string S.Replac
    15+ min read
  • Minimum length of string having all permutation of given string.
    Given a string [Tex]S [/Tex]where [Tex]1\leq length\; of\; S\leq 26 [/Tex]. Assume that all the characters in [Tex]S [/Tex]are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present
    4 min read
  • Minimum moves to make String Palindrome incrementing all characters of Substrings
    Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences