Minimize length of prefix of string S containing all characters of another string T
Last Updated :
08 Jun, 2021
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:
- Store the frequencies of T in a dictionary dictCount.
- Store the number of unique letters with a count greater than 0 as nUnique.
- Iterate over [0, N], and obtain the ith index character of S as ch.
- Decrease the count of ch from dictCount if it exists. If this count goes to 0, decrease nUnique by 1.
- If nUnique reaches 0, return the length traversed till then.
- After complete traversal of S, if nUnique still exceeds 0, print -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getPrefixLength(string srcStr,
string targetStr)
{
if (targetStr.length() == 0)
return 0;
transform(srcStr.begin(),
srcStr.end(),
srcStr.begin(), :: tolower );
transform(targetStr.begin(),
targetStr.end(),
targetStr.begin(), :: tolower );
map< char , int > dictCount;
int nUnique = 0;
for ( char ch: targetStr)
{
if (dictCount.find(ch) ==
dictCount.end())
{
nUnique += 1;
dictCount[ch] = 0;
}
dictCount[ch] += 1;
}
for ( int i = 0; i < srcStr.length(); i++)
{
char ch = srcStr[i];
if (dictCount.find(ch) ==
dictCount.end())
continue ;
dictCount[ch] -= 1;
if (dictCount[ch] == 0)
nUnique -= 1;
if (nUnique == 0)
return (i + 1);
}
return -1;
}
int main()
{
string S = "MarvoloGaunt" ;
string T = "Tom" ;
cout << getPrefixLength(S, T);
return 0;
}
|
Java
import java.util.*;
public class Main
{
public static int getPrefixLength(String srcStr, String targetStr)
{
if (targetStr.length() == 0 )
return 0 ;
srcStr = srcStr.toLowerCase();
targetStr = targetStr.toLowerCase();
HashMap<Character, Integer> dictCount = new HashMap<>();
int nUnique = 0 ;
for ( char ch : targetStr.toCharArray())
{
if (dictCount.containsKey(ch) != true )
{
nUnique += 1 ;
dictCount.put(ch, 0 );
}
dictCount.replace(ch, dictCount.get(ch) + 1 );
}
for ( int i = 0 ; i < srcStr.length(); i++)
{
char ch = srcStr.charAt(i);
if (dictCount.containsKey(ch) != true )
continue ;
dictCount.replace(ch, dictCount.get(ch) - 1 );
if (dictCount.get(ch) == 0 )
nUnique -= 1 ;
if (nUnique == 0 )
return (i + 1 );
}
return - 1 ;
}
public static void main(String[] args) {
String S = "MarvoloGaunt" ;
String T = "Tom" ;
System.out.println(getPrefixLength(S, T));
}
}
|
Python3
def getPrefixLength(srcStr, targetStr):
if ( len (targetStr) = = 0 ):
return 0
srcStr = srcStr.lower()
targetStr = targetStr.lower()
dictCount = dict ([])
nUnique = 0
for ch in targetStr:
if (ch not in dictCount):
nUnique + = 1
dictCount[ch] = 0
dictCount[ch] + = 1
for i in range ( len (srcStr)):
ch = srcStr[i]
if (ch not in dictCount):
continue
dictCount[ch] - = 1
if (dictCount[ch] = = 0 ):
nUnique - = 1
if (nUnique = = 0 ):
return (i + 1 )
return - 1
if __name__ = = "__main__" :
S = "MarvoloGaunt"
T = "Tom"
print (getPrefixLength(S, T))
|
C#
using System.Collections.Generic;
using System;
class GFG{
static int getPrefixLength( string srcStr,
string targetStr)
{
if (targetStr.Length == 0)
return 0;
srcStr = srcStr.ToLower();
targetStr = targetStr.ToLower();
Dictionary< char ,
int > dictCount = new Dictionary< char ,
int >();
int nUnique = 0;
foreach ( var ch in targetStr)
{
if (dictCount.ContainsKey(ch) != true )
{
nUnique += 1;
dictCount[ch] = 0;
}
dictCount[ch] += 1;
}
for ( int i = 0; i < srcStr.Length; i++)
{
char ch = srcStr[i];
if (dictCount.ContainsKey(ch) != true )
continue ;
dictCount[ch] -= 1;
if (dictCount[ch] == 0)
nUnique -= 1;
if (nUnique == 0)
return (i + 1);
}
return -1;
}
public static void Main()
{
string S = "MarvoloGaunt" ;
string T = "Tom" ;
Console.Write(getPrefixLength(S, T));
}
}
|
Javascript
<script>
function getPrefixLength(srcStr, targetStr) {
if (targetStr.length === 0) return 0;
srcStr = srcStr.toLowerCase();
targetStr = targetStr.toLowerCase();
var dictCount = {};
var nUnique = 0;
for (const ch of targetStr) {
if (dictCount.hasOwnProperty(ch) !== true ) {
nUnique += 1;
dictCount[ch] = 0;
}
dictCount[ch] += 1;
}
for ( var i = 0; i < srcStr.length; i++) {
var ch = srcStr[i];
if (dictCount.hasOwnProperty(ch) !== true ) continue ;
dictCount[ch] -= 1;
if (dictCount[ch] === 0) nUnique -= 1;
if (nUnique === 0) return i + 1;
}
return -1;
}
var S = "MarvoloGaunt" ;
var T = "Tom" ;
document.write(getPrefixLength(S, T));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...