The Wayback Machine - https://web.archive.org/web/20240914095135/https://www.geeksforgeeks.org/maximum-length-prefix-one-string-occurs-subsequence-another/
Open In App

Maximum length prefix of one string that occurs as subsequence in another

Last Updated : 20 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two strings s and t. The task is to find maximum length of some prefix of the string S which occur in string t as subsequence.

Examples : 

Input : s = "digger"
        t = "biggerdiagram"
Output : 3
digger
biggerdiagram
Prefix "dig" of s is longest subsequence in t.

Input : s = "geeksforgeeks"
        t = "agbcedfeitk"
Output : 4

A simple solutions is to consider all prefixes one by one and check if current prefix of s[] is a subsequence of t[] or not. Finally return length of the largest prefix.

An efficient solution is based on the fact that to find a prefix of length n, we must first find the prefix of length n – 1 and then look for s[n-1] in t. Similarly, to find a prefix of length n – 1, we must first find the prefix of length n – 2 and then look for s[n – 2] and so on. 
Thus, we keep a counter which stores the current length of prefix found. We initialize it with 0 and begin with the first letter of s and keep iterating over t to find the occurrence of the first letter. As soon as we encounter the first letter of s we update the counter and look for second letter. We keep updating the counter and looking for next letter, until either the string s is found or there are no more letters in t.

Below is the implementation of this approach: 

C++




// C++ program to find maximum
// length prefix of one string
// occur as subsequence in another
// string.
#include<bits/stdc++.h>
using namespace std;
 
// Return the maximum length
// prefix which is subsequence.
int maxPrefix(char s[], char t[])
{
    int count = 0;
 
    // Iterating string T.
    for (int i = 0; i < strlen(t); i++)
    {
        // If end of string S.
        if (count == strlen(s))
            break;
 
        // If character match,
        // increment counter.
        if (t[i] == s[count])
            count++;
    }
 
    return count;
}
 
// Driven Code
int main()
{
    char S[] = "digger";
    char T[] = "biggerdiagram";
 
    cout << maxPrefix(S, T)
         << endl;
 
    return 0;
}


Java




// Java program to find maximum
// length prefix of one string
// occur as subsequence in another
// string.
public class GFG {    
     
    // Return the maximum length
    // prefix which is subsequence.
    static int maxPrefix(String s,
                         String t)
    {
        int count = 0;
     
        // Iterating string T.
        for (int i = 0; i < t.length(); i++)
        {
            // If end of string S.
            if (count == s.length())
                break;
     
            // If character match, 
            // increment counter.
            if (t.charAt(i) == s.charAt(count))
                count++;
        }
     
        return count;
    }
     
    // Driver Code
    public static void main(String args[])
    {
        String S = "digger";
        String T = "biggerdiagram";
     
        System.out.println(maxPrefix(S, T));
    }
}
// This code is contributed by Sumit Ghosh


Python 3




# Python 3 program to find maximum
# length prefix of one string occur
# as subsequence in another string.
 
 
# Return the maximum length
# prefix which is subsequence.
def maxPrefix(s, t) :
    count = 0
 
    # Iterating string T.
    for i in range(0,len(t)) :
         
        # If end of string S.
        if (count == len(s)) :
            break
 
        # If character match,
        # increment counter.
        if (t[i] == s[count]) :
            count = count + 1
             
 
    return count
 
 
# Driver Code
S = "digger"
T = "biggerdiagram"
 
print(maxPrefix(S, T))
 
 
# This code is contributed
# by Nikita Tiwari.


C#




// C# program to find maximum
// length prefix of one string
// occur as subsequence in
// another string.
using System;
 
class GFG
{    
     
    // Return the maximum length prefix
    // which is subsequence.
    static int maxPrefix(String s,
                         String t)
    {
        int count = 0;
     
        // Iterating string T.
        for (int i = 0; i < t.Length; i++)
        {
            // If end of string S.
            if (count == s.Length)
                break;
     
            // If character match,
            // increment counter.
            if (t[i] == s[count])
                count++;
        }
     
        return count;
    }
     
    // Driver Code
    public static void Main()
    {
        String S = "digger";
        String T = "biggerdiagram";
     
        Console.Write(maxPrefix(S, T));
    }
}
 
// This code is contributed by nitin mittal


PHP




<?php
// PHP program to find maximum
// length prefix of one string
// occur as subsequence in another
// string.
 
// Return the maximum length
// prefix which is subsequence.
function maxPrefix($s, $t)
{
    $count = 0;
 
    // Iterating string T.
    for ($i = 0; $i < strlen($t); $i++)
    {
        // If end of string S.
        if ($count == strlen($s))
            break;
 
        // If character match,
        // increment counter.
        if ($t[$i] == $s[$count])
            $count++;
    }
 
    return $count;
}
 
// Driver Code
{
    $S = "digger";
    $T = "biggerdiagram";
 
    echo maxPrefix($S, $T) ;
 
    return 0;
}
 
// This code is contributed by nitin mittal.
?>


Javascript




<script>
 
// JavaScript program to find maximum
// length prefix of one string
// occur as subsequence in another
// string.
 
    // Return the maximum length
    // prefix which is subsequence.
    function maxPrefix(s,t)
    {
        let count = 0;
     
        // Iterating string T.
        for (let i = 0; i < t.length; i++)
        {
            // If end of string S.
            if (count == s.length)
                break;
     
            // If character match, 
            // increment counter.
            if (t[i] == s[count])
                count++;
        }
     
        return count;
    }
 
 
// Driver Code
 
    let S = "digger";
    let T = "biggerdiagram";
     
    document.write(maxPrefix(S, T));
         
</script>


Output

3

Time complexity: O(n)

Space complexity: O(1)

 



Previous Article
Next Article

Similar Reads

Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
Given an array arr[], the task is to count unordered pairs of positive integers (p, q) such that p occurs in the array at least q times and q occurs at least p times. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 (1, 1) is the only valid pair. Input: arr[] = {3, 3, 2, 2, 2} Output: 2 (2, 3) and (2, 2) are the only possible pairs. Approach: The
8 min read
Find length of longest subsequence of one string which is substring of another string
Given two strings X and Y. The task is to find the length of the longest subsequence of string X which is a substring in sequence Y. Examples: Input : X = "ABCD", Y = "BACDBDCD" Output : 3 "ACD" is longest subsequence of X which is substring of Y. Input : X = "A", Y = "A" Output : 1Recommended PracticeFind length of longest subsequenceTry It! PRERE
15+ min read
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k &gt; i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100) K-th index = 6 (Element at 6th index is 5.) Outp
14 min read
Find number of times a string occurs as a subsequence in given string
Given two strings, find the number of times the second string occurs in the first string, whether continuous or discontinuous. Examples: Input: string a = "GeeksforGeeks" string b = "Gks" Output: 4 Explanation: The four strings are - (Check characters marked in bold) GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeksRecommended PracticeString
15+ min read
Minimum number of removals required such that no subsequence of length 2 occurs more than once
Given a string S consisting of N lowercase characters, the task is to modify the given string such that no subsequence of length two repeats in the string by removing minimum number of characters. Examples: Input: S = "abcaadbcd"Output: abcdExplanation: Removing the characters at indices {2, 3, 4, 5, 6, 7} modifies the string to "abcd", that contai
7 min read
Minimize length of prefix of string S containing all characters of another string T
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"
7 min read
Minimum number of characters required to be added to a String such that all lowercase alphabets occurs as a subsequence in increasing order
Given a string S consisting of N characters, the task is to find the minimum number of characters that must be added to S such that all lowercase alphabets occur as a subsequence in increasing order in S. Examples: Input: S = "axyabzaxd"Output: 22Explanation:The characters from b to w (bcdefghijklmnopqrstuvw) whose count is 22, is missing in the gi
7 min read
Check if it is possible to go from one point to another by choosing a Subsequence of steps of smallest length
Given a string S of characters R, L, U, D, along with integers X1, Y1, X2, Y2. In String S, 'R', 'L', 'U', and'D' denote right, left, up, and down steps from the current position. Then the task is to output the length of the smallest length subsequence of steps from S, such that following those steps we can reach from (X1, Y1) to (X2, Y2). If it is
9 min read
Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = "abcdefababaef", B = "abf"Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = "abcdefababaef", B = "aef"Output: 3 Recommended: Please solve it on "PRACT
12 min read
Find length of smallest substring of a given string which contains another string as subsequence
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. If there are multiple such substrings in A, return the substring that has the smallest starting index. Examples : Input : A = "abcedbaced" B = "bed"Output : "bced"Explanation : The substring A[2 : 5] is the shortest substring that contains the stri
15 min read
Maximum length subsequence such that adjacent elements in the subsequence have a common factor
Given an array arr[], the task is to find the maximum length of a subsequence such that the adjacent elements in the subsequence have a common factor. Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 } Output: 5Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 } Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 } Output: 6Max length subsequence
9 min read
Longest subsequence where each character occurs at least k times
Given a string 's' and an integer k, find other string 't' such that 't' is the largest subsequence of given string 's' and each character of 't' must occur at least k times in string s. Examples : Input : s = "geeksforgeeks" k = 2 Output : geeksgeeks Input : s = "baaabaacba" k = 3 Output : baaabaaba A simple solution is to generate all subsequence
5 min read
Lexicographically largest subsequence such that every character occurs at least k times
Given a string S and an integer K. The task is to find lexicographically largest subsequence of S, say T, such that every character in T must occur at least K times. Examples: Input : S = "banana", K = 2. Output : nn Possible subsequence where each character exists at least 2 times are: From the above subsequences, "nn" is the lexicographically lar
7 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Length of longest subsequence such that prefix sum at every element remains greater than zero
Given an array arr[] of size N and an integer X, the task is to find the length of the longest subsequence such that the prefix sum at every element of the subsequence remains greater than zero. Example: Input: arr[] = {-2, -1, 1, 2, -2}, N = 5Output: 3Explanation: The sequence can be made of elements at index 2, 3 and 4. The prefix sum at every el
6 min read
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1. Examples: Input: S = "acbbebcg"Output: 5Explanation: The longest subsequence of required type is "cbbbc", whose length is 5.Th
6 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Count maximum occurrence of subsequence in string such that indices in subsequence is in A.P.
Given a string S, the task is to count the maximum occurrence of subsequences in the given string such that the indices of the characters of the subsequence are Arithmetic Progression. Examples: Input: S = "xxxyy" Output: 6 Explanation: There is a subsequence "xy", where indices of each character of the subsequence are in A.P. The indices of the di
12 min read
Rearrange a string S1 such that another given string S2 is not its subsequence
Given two strings S1 and S2 of size N and M respectively, the task is to rearrange characters in string S1 such that S2 is not a subsequence of it. If it is not possible to make such rearrangements, then print "-1". Otherwise, print the rearranged string S1. Examples: Input: S1 = "abcd", S2 = "ab"Output: "dcba"Explanation:Rearrange the string S1 as
10 min read
Minimize removals to remove another string as a subsequence of a given string
Given two strings str and X of length N and M respectively, the task is to find the minimum characters required to be removed from the string str such that string str doesn't contain the string X as a subsequence. Examples: Input: str = "btagd", X = "bad"Output: 1Explanation:String "btag" has does not contain "bad" as a subsequence. Therefore, only
14 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Find the longest subsequence of a string that is a substring of another string
Given two strings X and Y consisting of N and M characters, the task is to find the longest subsequence of a string X which is a substring of the string Y. Examples: Input: X = "ABCD", Y = "ACDBDCD"Output: ACDExplanation:"ACD" is longest subsequence of X which is substring of Y. Input: X = A, Y = AOutput: A Naive Approach: The simplest approach to
10 min read
Check if a string is a subsequence of another string ( using Stacks )
Given a string S, the task is to check if the string target is a subsequence of string S or not, using a Stack. Examples: Input: S = ”KOTTAYAM”, target = ”KOTA”Output: YesExplanation: “KOTA” is a subsequence of “KOTTAYAM”. Input: S = ”GEEKSFORGEEKS”, target =”FORFOR”Output: No Approach: Follow the steps to solve the problem: Initialize a stack s.It
9 min read
Maximum length Subsequence with alternating sign and maximum Sum
Given an array arr[] of size n having both positive and negative integer excluding zero. The task is to find the subsequence with an alternating sign having maximum size and maximum sum that is, in a subsequence sign of each adjacent element is opposite for example if the first one is positive then the second one has to be negative followed by anot
7 min read
Return a Palindromic String after removing minimum length Prefix from given String
Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanation: We can remove the prefix "a" from the string "a
5 min read
Queries to print the character that occurs the maximum number of times in a given range
Given a string S of size N and Q queries. Every query consists of L and R ( 0 &lt; = L &lt; = R &lt; N ) . The task is to print the character that occurs the maximum number of times in the given range. If there are multiple characters that occur maximum number of times then print the lexicographically smallest of them. Note: S consists of lowercase
8 min read
Number of permutations of a string in which all the occurrences of a given character occurs together
Given a string 's' and a character 'c', the task is to find the number of permutations of the string in which all the occurrences of the character 'c' will be together (one after another). Examples : Input: Str = "AKA" ch = 'A' Output: 2 Explanation: All the unique permutations of AKA are : AKA, AAK and KAA 'A' comes consecutively only twice. Hence
9 min read
Number of times the given string occurs in the array in the range [l, r]
Given an array of strings arr[] and two integers l and r, the task is to find the number of times the given string str occurs in the array in the range [l, r] (1-based indexing). Note that the strings contain only lowercase letters.Examples: Input: arr[] = {"abc", "def", "abc"}, L = 1, R = 2, str = "abc" Output: 1Input: arr[] = {"abc", "def", "abc"
10 min read
Minimum count of 0s to be removed from given Binary string to make all 1s occurs consecutively
Given a binary string S of size N, the task is to find the minimum numbers of 0s that must be removed from the string S such that all the 1s occurs consecutively. Examples: Input: S = "010001011" Output: 4 Explanation: Removing the characters { S[2], S[3], S[4], S[6] } from the string S modifies the string S to "01111". Therefore, the required outp
7 min read
Check if substring "10" occurs in the given binary string in all possible replacements of '?' with 1 or 0
Given a string S consisting of only '0', '1' and '?', the task is to check if there exists a substring "10" in every possible replacement of the character '?' with either 1 or 0. Examples: Input: S = "1?0"Output: YesExplanation:Following are all the possible replacements of '?': Replacing the '?' with 0 modifies the string to "100". In the modifies
7 min read