The Wayback Machine - https://web.archive.org/web/20241116223650/https://www.geeksforgeeks.org/find-given-string-can-represented-substring-iterating-substring-n-times/
Open In App

Find if a given string can be represented from a substring by iterating the substring “n” times

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

Given a string ‘str’, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

Examples: 

Input: str = "abcabcabc"
Output: true
The given string is 3 times repetition of "abc"

Input: str = "abadabad"
Output: true
The given string is 2 times repetition of "abad"

Input: str = "aabaabaabaab"
Output: true
The given string is 4 times repetition of "aab"

Input: str = "abcdabc"
Output: false

Source: Google Interview Question 

We strongly recommend that you click here and practice it, before moving on to the solution.

There can be many solutions to this problem. The challenging part is to solve the problem in O(n) time. Below is a O(n) algorithm.

Let the given string be ‘str’ and length of given string be ‘n’.

  1. Find the length of the longest proper prefix of ‘str’ which is also a suffix. Let the length of the longest proper prefix suffix be ‘len’. This can be computed in O(n) time using pre-processing step of KMP string matching algorithm.
  2. If value of ‘n – len’ divides n (or ‘n % (n-len)’ is 0), then return true, else return false.
    In case of ‘true’ , the substring ‘str[0..n-len-1]’ is the substring that repeats n/(n-len) times.

Let us take few examples. Input: str = “ABCDABCD”, n = 8 (Number of characters in ‘str’)  The value of len is 4 (“ABCD” is the longest substring which is both prefix and suffix)  Since (n-len) divides n, the answer is true. Input: str = “ABCDABC”, n = 7 (Number of characters in ‘str’)  The value of len is 3 (“ABC” is the longest substring which is both prefix and suffix)  Since (n-len) doesn’t divides n, the answer is false. Input: str = “ABCABCABCABCABC”, n = 15 (Number of characters in ‘str’)  The value of len is 12 (“ABCABCABCABC” is the longest substring which is both prefix and suffix)  Since (n-len) divides n, the answer is true.

How does this work? 
length of longest proper prefix-suffix (or len) is always between 0 to n-1. If len is n-1, then all characters in string are same. For example len is 3 for “AAAA”. If len is n-2 and n is even, then two characters in string repeat n/2 times. For example “ABABABAB”, length of lps is 6. The reason is if the first n-2 characters are same as last n-2 character, the starting from the first pair, every pair of characters is identical to the next pair. The following diagram demonstrates same for substring of length 4.

isRepeat

Following is the implementation of above algorithm: 

C++




// A C++ program to check if a string is 'n' times
// repetition of one of its substrings
#include <bits/stdc++.h>
using namespace std;
 
// A utility function to fill lps[] or compute prefix
// function used in KMP string matching algorithm. Refer
// details
void computeLPSArray(char str[], int M, int lps[])
{
    // length of the previous longest prefix suffix
    int len = 0;
    int i;
 
    lps[0] = 0; // lps[0] is always 0
    i = 1;
 
    // the loop calculates lps[i] for i = 1 to M-1
    while (i < M) {
        if (str[i] == str[len]) {
            len++;
            lps[i] = len;
            i++;
        }
        else // (pat[i] != pat[len])
        {
            if (len != 0) {
                // This is tricky. Consider the example
                // AAACAAAA and i = 7.
                len = lps[len - 1];
 
                // Also, note that we do not increment i
                // here
            }
            else // if (len == 0)
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}
 
// Returns true if str is repetition of one of its
// substrings else return false.
bool isRepeat(char str[])
{
    // Find length of string and create an array to
    // store lps values used in KMP
    int n = strlen(str);
    int lps[n];
 
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(str, n, lps);
 
    // Find length of longest suffix which is also
    // prefix of str.
    int len = lps[n - 1];
 
    // If there exist a suffix which is also prefix AND
    // Length of the remaining substring divides total
    // length, then str[0..n-len-1] is the substring that
    // repeats n/(n-len) times (Readers can print substring
    // and value of n/(n-len) for more clarity.
    return (len > 0 && n % (n - len) == 0) ? true : false;
}
 
// Driver program to test above function
int main()
{
    char txt[][100]
        = { "ABCABC",        "ABABAB",   "ABCDABCD",
            "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC",
            "ABCDABC" };
    int n = sizeof(txt) / sizeof(txt[0]);
    for (int i = 0; i < n; i++)
        isRepeat(txt[i]) ? cout << "True\n"
                         : cout << "False\n";
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// A C++ program to check if a string is 'n' times
// repetition of one of its substrings
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
 
// A utility function to fill lps[] or compute prefix
// function used in KMP string matching algorithm. Refer
// details
void computeLPSArray(char str[], int M, int lps[])
{
    // length of the previous longest prefix suffix
    int len = 0;
    int i;
 
    lps[0] = 0; // lps[0] is always 0
    i = 1;
 
    // the loop calculates lps[i] for i = 1 to M-1
    while (i < M) {
        if (str[i] == str[len]) {
            len++;
            lps[i] = len;
            i++;
        }
        else // (pat[i] != pat[len])
        {
            if (len != 0) {
                // This is tricky. Consider the example
                // AAACAAAA and i = 7.
                len = lps[len - 1];
 
                // Also, note that we do not increment i
                // here
            }
            else // if (len == 0)
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}
 
// Returns true if str is repetition of one of its
// substrings else return false.
bool isRepeat(char str[])
{
    // Find length of string and create an array to
    // store lps values used in KMP
    int n = strlen(str);
    int lps[n];
 
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(str, n, lps);
 
    // Find length of longest suffix which is also
    // prefix of str.
    int len = lps[n - 1];
 
    // If there exist a suffix which is also prefix AND
    // Length of the remaining substring divides total
    // length, then str[0..n-len-1] is the substring that
    // repeats n/(n-len) times (Readers can print substring
    // and value of n/(n-len) for more clarity.
    return (len > 0 && n % (n - len) == 0) ? true : false;
}
 
// Driver program to test above function
int main()
{
    char txt[][100]
        = { "ABCABC",        "ABABAB",   "ABCDABCD",
            "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC",
            "ABCDABC" };
    int n = sizeof(txt) / sizeof(txt[0]);
    for (int i = 0; i < n; i++)
        isRepeat(txt[i]) ? printf("True\n")
                         : printf("False\n");
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to check if a string is 'n'
// times repetition of one of its substrings
import java.io.*;
class GFG {
 
    // A utility function to fill lps[] or compute
    // prefix function used in KMP string matching
    // algorithm. Refer
    // for details
    static void computeLPSArray(String str, int M,
                                int lps[])
    {
        // length of the previous
        // longest prefix suffix
        int len = 0;
 
        int i;
 
        lps[0] = 0; // lps[0] is always 0
        i = 1;
 
        // the loop calculates lps[i]
        // for i = 1 to M-1
        while (i < M) {
            if (str.charAt(i) == str.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {
                if (len != 0) {
                    // This is tricky. Consider the
                    // example AAACAAAA and i = 7.
                    len = lps[len - 1];
 
                    // Also, note that we do
                    // not increment i here
                }
                else // if (len == 0)
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
    }
 
    // Returns true if str is repetition of
    // one of its substrings else return false.
    static boolean isRepeat(String str)
    {
        // Find length of string and create
        // an array to store lps values used in KMP
        int n = str.length();
        int lps[] = new int[n];
 
        // Preprocess the pattern (calculate lps[] array)
        computeLPSArray(str, n, lps);
 
        // Find length of longest suffix
        // which is also prefix of str.
        int len = lps[n - 1];
 
        // If there exist a suffix which is also
        // prefix AND Length of the remaining substring
        // divides total length, then str[0..n-len-1]
        // is the substring that repeats n/(n-len)
        // times (Readers can print substring and
        // value of n/(n-len) for more clarity.
        return (len > 0 && n % (n - len) == 0) ? true
                                               : false;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        String txt[]
            = { "ABCABC",        "ABABAB",   "ABCDABCD",
                "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC",
                "ABCDABC" };
        int n = txt.length;
        for (int i = 0; i < n; i++) {
            if (isRepeat(txt[i]) == true)
                System.out.println("True");
            else
                System.out.println("False");
        }
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# A Python program to check if a string is 'n' times
# repetition of one of its substrings
 
# A utility function to fill lps[] or compute prefix function
# used in KMP string matching algorithm. Refer
def computeLPSArray(string, M, lps):
    length = 0        # length of the previous longest prefix suffix
    i = 1
 
    lps[0] = 0    # lps[0] is always 0
 
    # the loop calculates lps[i] for i = 1 to M-1
    while i < M:
        if string[i] == string[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:           
                # This is tricky. Consider the example AAACAAAA
                # and i = 7.
                length = lps[length-1]
 
                # Also, note that we do not increment i here
            else:
                lps[i] = 0
                i += 1
 
# Returns true if string is repetition of one of its substrings
# else return false.
def isRepeat(string):
    # Find length of string and create an array to
    # store lps values used in KMP
    n = len(string)
    lps = [0] * n
 
    # Preprocess the pattern (calculate lps[] array)
    computeLPSArray(string, n, lps)
 
    # Find length of longest suffix which is also
    # prefix of str.
    length = lps[n-1]
 
    # If there exist a suffix which is also prefix AND
    # Length of the remaining substring divides total
    # length, then str[0..n-len-1] is the substring that
    # repeats n/(n-len) times (Readers can print substring
    # and value of n/(n-len) for more clarity.
    if length > 0 and n%(n-length) == 0:
        return True
    else:
        False
 
# Driver program
txt = ["ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS",
        "GEEKGEEK", "AAAACAAAAC", "ABCDABC"]
n = len(txt)
for i in range(n):
    if isRepeat(txt[i]):
        print (True)
    else:
        print (False)
 
# This code is contributed by BHAVYA JAIN


C#




// C# program to check if a string is 'n'
// times repetition of one of its substrings
using System;
 
class GFG {
     
    // A utility function to fill lps[] or
    // compute prefix function used in KMP
    // string matching algorithm. Refer
    // for details
    static void computeLPSArray(String str, int M,
                                         int []lps)
    {
         
        // length of the previous
        // longest prefix suffix
        int len = 0;
         
        int i;
     
        lps[0] = 0; // lps[0] is always 0
        i = 1;
     
        // the loop calculates lps[i]
        // for i = 1 to M-1
        while (i < M)
        {
            if (str[i] == str[len])
            {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {
                if (len != 0)
                {
                     
                    // This is tricky. Consider the
                    // example AAACAAAA and i = 7.
                    len = lps[len-1];
         
                    // Also, note that we do
                    // not increment i here
                }
                else // if (len == 0)
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
    }
     
    // Returns true if str is repetition of
    // one of its substrings else return false.
    static bool isRepeat(String str)
    {
         
        // Find length of string and create
        // an array to store lps values used
        // in KMP
        int n = str.Length;
        int[] lps = new int[n];
     
        // Preprocess the pattern (calculate
        // lps[] array)
        computeLPSArray(str, n, lps);
     
        // Find length of longest suffix
        // which is also prefix of str.
        int len = lps[n-1];
 
        // If there exist a suffix which is also
        // prefix AND Length of the remaining
        // substring divides total length, then
        // str[0..n-len-1] is the substring that
        // repeats n/(n-len) times (Readers can
        // print substring and value of n/(n-len)
        // for more clarity.
        return (len > 0 && n % (n - len) == 0)
                               ? true : false;
    }
     
    // Driver program to test above function
    public static void Main()
    {
        String[] txt = {"ABCABC", "ABABAB",
                    "ABCDABCD", "GEEKSFORGEEKS",
                       "GEEKGEEK", "AAAACAAAAC",
                                     "ABCDABC"};
        int n = txt.Length;
         
        for (int i = 0; i < n; i++)
        {
            if(isRepeat(txt[i]) == true)
                Console.WriteLine("True");
            else
                Console.WriteLine("False");
        }
    }
}
 
// This code is contributed by Sam007.


Javascript




<script>
 
    // Javascript program to check if a string is 'n'
    // times repetition of one of its substrings
     
    // A utility function to fill lps[] or
    // compute prefix function used in KMP
    // string matching algorithm. Refer
    // for details
    function computeLPSArray(str, M, lps)
    {
           
        // length of the previous
        // longest prefix suffix
        let len = 0;
           
        let i;
       
        lps[0] = 0; // lps[0] is always 0
        i = 1;
       
        // the loop calculates lps[i]
        // for i = 1 to M-1
        while (i < M)
        {
            if (str[i] == str[len])
            {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {
                if (len != 0)
                {
                       
                    // This is tricky. Consider the
                    // example AAACAAAA and i = 7.
                    len = lps[len-1];
           
                    // Also, note that we do
                    // not increment i here
                }
                else // if (len == 0)
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
    }
       
    // Returns true if str is repetition of
    // one of its substrings else return false.
    function isRepeat(str)
    {
           
        // Find length of string and create
        // an array to store lps values used
        // in KMP
        let n = str.length;
        let lps = new Array(n);
        lps.fill(0);
       
        // Preprocess the pattern (calculate
        // lps[] array)
        computeLPSArray(str, n, lps);
       
        // Find length of longest suffix
        // which is also prefix of str.
        let len = lps[n-1];
   
        // If there exist a suffix which is also
        // prefix AND Length of the remaining
        // substring divides total length, then
        // str[0..n-len-1] is the substring that
        // repeats n/(n-len) times (Readers can
        // print substring and value of n/(n-len)
        // for more clarity.
        return (len > 0 && n % (n - len) == 0)
                               ? true : false;
    }
     
    let txt = ["ABCABC", "ABABAB",
                    "ABCDABCD", "GEEKSFORGEEKS",
                       "GEEKGEEK", "AAAACAAAAC",
                                     "ABCDABC"];
    let n = txt.length;
 
    for (let i = 0; i < n; i++)
    {
      if(isRepeat(txt[i]) == true)
        document.write("True" + "</br>");
      else
        document.write("False" + "</br>");
    }
 
</script>


Output

True
True
True
False
True
True
False

Time Complexity: Time complexity of the above solution is O(n) as it uses KMP preprocessing algorithm which is linear time algorithm.
Auxiliary Space: O(n) because it is using extra space for array “lps”

Another approach:

Above problem can be solved with out using KMP algorithm and extra space.

This approach uses two pointers to check the minimum period of a String as a first step. Period of a String is the length of prefix substring which can be repeated x(x=length/period) times to construct the given string. 

for eg: Input string “abcabcabcabc” is having a period 3. which means we can construct the given string by repeating first 3 characters  4 (length/3=4) number of times.

Approach:

  1. Initially set first pointer – i at 0th index of given string and second pointer – j at 1st index.
  2. check the characters at both index. if both matches, take period as (j-i) and increment i and j.
  3. if doesn’t match, Once again check if current character matches with first character at 0th index. if matches, update period as j(j-0=j) and set i to next character.
  4. f both characters not matches, set i to 0 and update period to -1.
  5. At the end check if the calculated period exactly divides the length of the string. if not, update period to -1. This check eliminates the presence of strings ending with suffix less than the period. for e.g period for the string “GEEKSFORGEEKS” is calculated as 8 but the suffix string(GEEKS) is having 5 characters only and is incomplete.

Implementation:

C++




/*package whatever //do not write package name here */
#include <bits/stdc++.h>
using namespace std;
 
int findPeriod(string A)
{
    int length = A.size();
 
    // Initially consider there is no period for given
    // String
    int period = -1;
 
    /*set two pointers one(i) at
    index 0 and other(j) at index 1. increment j till
    first character is obtained in the string*/
    int i = 0;
    for (int j = 1; j < length; j++) {
        int currChar = A[j];
        int comparator = A[i];
 
        /*If current character matches with first
         *character
         *update period as the difference of j and i*/
        if (currChar == comparator) {
            period = (j - i);
            i++;
        }
 
        /* if any mismatch occurs in between set i to
         * zero also check if current character again
         * matches
         * with starting character. If matches, update
         * period*/
        else {
            if (currChar == A[0]) {
                i = 1;
                period = j;
            }
            else {
                i = 0;
                period = -1;
            }
        }
    }
 
    /*check if the period is exactly dividing
     * string if not reset the period to -1
     * this eliminates partial substrings like
     * e.g string -"GEEKSFORGEEKS" */
 
    period = (length % period != 0) ? -1 : period;
    return period;
}
int main()
{
    vector<string> testStrings
        = { "ABCABC",        "ABABAB",   "ABCDABCD",
            "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC",
            "ABCDABC" };
    int n = testStrings.size();
    for (int i = 0; i < n; i++) {
        if (findPeriod(testStrings[i]) == -1)
            cout << "false\n";
        else
            cout << "True\n";
    }
 
    return 0;
}
 
    // This code is contributed by rakeshsahni


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    public static int findPeriod(String A)
    {
        int length = A.length();
 
        // Initially consider there is no period for given
        // String
        int period = -1;
 
        /*set two pointers one(i) at
        index 0 and other(j) at index 1. increment j till
        first character is obtained  in the string*/
        int i = 0;
        for (int j = 1; j < length; j++) {
            int currChar = A.charAt(j);
            int comparator = A.charAt(i);
 
            /*If current character matches with first
             *character
             *update period as the difference of j and i*/
            if (currChar == comparator) {
                period = (j - i);
                i++;
            }
 
            /* if any mismatch occurs in between set i to
             * zero also check if current character again
             * matches
             * with starting character. If matches, update
             * period*/
            else {
                if (currChar == A.charAt(0)) {
                    i = 1;
                    period = j;
                }
                else {
                    i = 0;
                    period = -1;
                }
            }
        }
 
        /*check if the period is exactly dividing
         * string if not reset the period to -1
         * this eliminates partial substrings like
         *  e.g string -"GEEKSFORGEEKS"  */
 
        period = (length % period != 0) ? -1 : period;
        return period;
    }
    public static void main(String[] args)
    {
        String[] testStrings
            = { "ABCABC",        "ABABAB",   "ABCDABCD",
                "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC",
                "ABCDABC" };
        int n = testStrings.length;
        for (int i = 0; i < n; i++) {
            if (findPeriod(testStrings[i]) == -1)
                System.out.println("false");
            else
                System.out.println("True");
        }
    }
}


Python3




def findPeriod(A):
 
    length = len(A)
 
    # Initially consider there is no period for given
    # String
    period = -1
 
    # set two pointers one(i) at
    # index 0 and other(j) at index 1. increment j till
    # first character is obtained in the string
    i = 0
    for j in range(1,length):
        currChar = A[j]
        comparator = A[i]
 
        # If current character matches with first
        # character
        # update period as the difference of j and i
        if (currChar == comparator):
            period = (j - i)
            i += 1
 
        #  if any mismatch occurs in between set i to
        #  zero also check if current character again
        #  matches
        #  with starting character. If matches, update
        #  period
        else:
            if (currChar == A[0]):
                i = 1
                period = j
            else:
                i = 0
                period = -1
 
    #  check if the period is exactly dividing
    #  string if not reset the period to -1
    #  this eliminates partial substrings like
    #  e.g string -"GEEKSFORGEEKS"
 
    period = -1 if (length % period != 0) else period
    return period
 
testStrings = [ "ABCABC",     "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" ]
n = len(testStrings)
for i in range(n):
    if (findPeriod(testStrings[i]) == -1):
        print("false")
    else:
        print("True")
 
# This code is contributed by shinjanpatra


C#




using System;
 
public class GFG{
  public static int findPeriod(String A)
  {
    int length = A.Length;
 
    // Initially consider there is no period for given
    // String
    int period = -1;
 
    /*set two pointers one(i) at
        index 0 and other(j) at index 1. increment j till
        first character is obtained  in the string*/
    int i = 0;
    for (int j = 1; j < length; j++) {
      int currChar = A[j];
      int comparator = A[i];
 
      /*If current character matches with first
             *character
             *update period as the difference of j and i*/
      if (currChar == comparator) {
        period = (j - i);
        i++;
      }
 
      /* if any mismatch occurs in between set i to
             * zero also check if current character again
             * matches
             * with starting character. If matches, update
             * period*/
      else {
        if (currChar == A[0]) {
          i = 1;
          period = j;
        }
        else {
          i = 0;
          period = -1;
        }
      }
    }
 
    /*check if the period is exactly dividing
         * string if not reset the period to -1
         * this eliminates partial substrings like
         *  e.g string -"GEEKSFORGEEKS"  */
 
    period = (length % period != 0) ? -1 : period;
    return period;
  }
  static public void Main (){
 
    // Code
    String[] txt = {"ABCABC", "ABABAB",
                    "ABCDABCD", "GEEKSFORGEEKS",
                    "GEEKGEEK", "AAAACAAAAC",
                    "ABCDABC"};
    int n = txt.Length;
 
    for (int i = 0; i < n; i++)
    {
      if(findPeriod(txt[i]) == -1)
        Console.WriteLine("False");
      else
        Console.WriteLine("True");
    }
  }
}
 
// This code is contributed by lokeshpotta20.


Javascript




<script>
 
function findPeriod(A)
{
    let length = A.length;
 
    // Initially consider there is no period for given
    // String
    let period = -1;
 
    /*set two pointers one(i) at
    index 0 and other(j) at index 1. increment j till
    first character is obtained in the string*/
    let i = 0;
    for (let j = 1; j < length; j++) {
        let currChar = A[j];
        let comparator = A[i];
 
        /*If current character matches with first
        *character
        *update period as the difference of j and i*/
        if (currChar == comparator) {
            period = (j - i);
            i++;
        }
 
        /* if any mismatch occurs in between set i to
        * zero also check if current character again
        * matches
        * with starting character. If matches, update
        * period*/
        else {
            if (currChar == A[0]) {
                i = 1;
                period = j;
            }
            else {
                i = 0;
                period = -1;
            }
        }
    }
 
    /*check if the period is exactly dividing
    * string if not reset the period to -1
    * this eliminates partial substrings like
    * e.g string -"GEEKSFORGEEKS" */
 
    period = (length % period != 0) ? -1 : period;
    return period;
}
// driver code
 
let testStrings    = [ "ABCABC",     "ABABAB", "ABCDABCD","GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC","ABCDABC" ];
let n = testStrings.length;
for (let i = 0; i < n; i++) {
    if (findPeriod(testStrings[i]) == -1)
        document.write("false","</br>");
    else
        document.write("True","</br>");
}
 
 
// This code is contributed by shinjanpatra
 
</script>


Output

True
True
True
false
True
True
false

Time Complexity : O(n)

Auxiliary Space : O(1)



Similar Reads

Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
Given three integers X, Y and Z, the task is to find the sum of all the numbers formed having 4 at most X times, 5 at most Y times, and 6 at most Z times, under mod 10^9+7.Examples: Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 Input: X = 4, Y = 5, Z = 6 Outpu
9 min read
Maximize the number of times a character can be removed from substring 01 from given Binary String
Given a binary string S of size N, the task is to find the maximum number of operations that can be performed on S, by selecting any substring "01" and removing any character from it in a single move, reducing the length of the string by 1. Examples: Input: S = "001111", N = 6Output: 5Explanation: One way to perform the operations is: Select the su
6 min read
Shortest String formed by concatenating string A x times and B y times such that n(A)*x = n(B)*y
Given two strings A and B, the task is to find the shortest string which is some multiple of both A and B. A string X is said to be a multiple of string Y if string X can be formed by the concatenation of multiple occurrences of string Y. Example: Input: A = "aaa", B= "aa"Output: aaaaaaExplanation: Multiplying A two times and B three times will res
7 min read
Maximum number of times a given string needs to be concatenated to form a substring of another string
Given two strings S1 and S2 of length N and M respectively, the task is to find the maximum value of times the string S2 needs to be concatenated, such that it is a substring of the string S1. Examples: Input: S1 = "ababc", S2 = "ab"Output: 2Explanation: After concatenating S2 exactly twice, the string modifies to "abab". Therefore, string "abab" i
12 min read
Find the string among given strings represented using given encryption pattern
Given an array of strings arr[] of size N and an encrypted string str, the task is to find the correct string from the given array of strings whose encryption will give str where str is encrypted using the following rules: The starting characters form an integer representing the number of uppercase symbols In the decrypted string.The next 3 charact
8 min read
Find the smallest positive number which can not be represented by given digits
Given an array arr[] of size 10 where arr[i] represents the frequency of the digit i. The task is to find the smallest positive number which can not be represented by the given digits. Examples: Input: arr[] = {2, 1, 1, 4, 0, 6, 3, 2, 2, 2} Output: 4 Since the count of 4th digit is 0. So 4 can not be made. Input : arr[] = {0, 1, 1, 1, 1, 1, 1, 1, 1
8 min read
Check if a given number can be represented in given a no. of digits in any base
Given a number and no. of digits to represent the number, find if the given number can be represented in given no. of digits in any base from 2 to 32.Examples : Input: 8 4 Output: Yes Possible in base 2 as 8 in base 2 is 1000 Input: 8 2 Output: Yes Possible in base 3 as 8 in base 3 is 22 Input: 8 3 Output: No Not possible in any base We strongly re
12 min read
Iterating over all possible combinations in an Array using Bits
There arise several situations while solving a problem where we need to iterate over all possible combinations of an array. In this article, we will discuss the method of using bits to do so.For the purpose of explaining, consider the following question: Given an array b[] = {2, 1, 4}. The task is to check if there exists any combination of element
7 min read
Check if the given array can be reduced to zeros with the given operation performed given number of times
Given an array arr[] of N integers and an integer K, the task is to find whether the given array elements can be made 0 if the given operation is applied exactly K times. In a single operation, the smallest element from the array will be subtracted from all the non-zero elements of the array.Examples: Input: arr[] = {1, 1, 2, 3}, K = 3 Output: Yes
6 min read
Smallest String consisting of a String S exactly K times as a Substring
Given a string S of length N and integer K, find the smallest length string which contains the string S as a sub string exactly K times. Examples: Input: S = "abba", K = 3 Output: abbabbabba Explanation: The string "abba" occurs K times in the string abbabbabba, i.e. {abbabbabba, abbabbabba, abbabbabba} Input: S = "geeksforgeeks", K = 3 Output: "ge
6 min read
Build a DFA to accept a binary string containing "01" i times and "1" 2j times
Given a binary string str, the task is to build a DFA that accepts given binary string if it contains "01" i times and "1" 2j times, i.e., [Tex]L={(01)^i (1)^{2j} \text{ where }i\geq1\text{ and }j\geq1} [/Tex] Examples: Input: str = "011111" Output: Accepted Explanation: The string follows the language as: (01)1(1)2*2 Input: str = "01111" Output: N
9 min read
Lexicographically Kth-smallest string having 'a' X times and 'b' Y times
Given three non-negative integers, X, Y, and K, the task is to find the Kth smallest lexicographical string having X occurrences of character 'a' and Y occurrences of character 'b'. Examples: Input: X = 2, Y = 3, K = 3Output: abbabExplanation: First lexicographical smallest string = "aabbb".Second lexicographical smallest string = "ababb".Third lex
15+ min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Find character at Kth index by appending S1 (M) times and S2 (M+1) times
Given two strings, S1 and S2 and an integer K.A string str can be made by performing the following operations: Take an Empty String InitiallyAppend S1 one timesAppend S2 two timesAppend S1 three timesAppend S2 four timesAppend S1 five timesAppend S2 six timesYou can keep building this string until it reaches K The task is to find the character at t
15 min read
Find two Fibonacci numbers whose sum can be represented as N
Given an even number N, the task is to find two Fibonacci numbers whose sum can be represented as N. There may be several combinations possible. Print only first such pair. If there is no solution then print -1.Examples: Input: N = 90 Output: 1, 89 Explanation: The first pair with whose sum is equal to 90 is {1, 89}Input: N = 74 Output: -1 Approach
6 min read
Maximum time in HH:MM:SS format that can be represented by given six digits
Given an array arr[] consisting of six integer digits only, the task is to return the maximum time in a 24-hour format that can be represented using the digits from the given array. Note: The minimum time in 24-hour format is 00:00:00, and the maximum is 23:59:59. If a valid time cannot be formed, then print -1. Examples: Input: arr[] = {0, 2, 1, 9
9 min read
Check if given number can be represented as sum of two great numbers
We are given a number N. We need to check if the given number N can be represented as sum of two Great numbers. If yes then print those two great numbers else print no. Great numbers are those which are represented in the form : ((b)*(b+1)*(2*b+1))/6 where b is a natural number. Examples: Input : N = 35Output : 5 and 30Input : 105Output : 14 and 91
7 min read
Count of times second string can be formed from the characters of first string
Given two strings str and patt, the task is to find the count of times patt can be formed using the characters of str. Examples: Input: str = "geeksforgeeks", patt = "geeks" Output: 2 "geeks" can be made at most twice from the characters of "geeksforgeeks". Input: str = "abcbca", patt = "aabc" Output: 1 Approach: Count the frequency of all the char
6 min read
Check if a string can be converted to another given string by removal of a substring
Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print “YES”. Otherwise, print “NO”. Example: Input: S = “abcdef”, T = “abc” Output: YES Explanation: Removing the substring { S[3], …, S[5] } mod
7 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
Check if given array can be made 0 with given operations performed any number of times
Given an array arr[] containing N integers, the task is to find whether all the elements of the given array can be made 0 by following operations: Increment any element by 2.Subtract the minimum element of the array from all elements in the array.The above operations can be performed any number times. If all the elements of the given array can beco
6 min read
Minimize count of 0s in Binary String by changing K-size substring to 1s at most Q times
Given a binary string S having N characters and two integers K and Q, the task is to find the minimum number of remaining zeroes after at most Q operations, such that in each operation, choose any substring of size at most K and change all its elements to 1. Example: Input: S = 000111, K = 2, Q = 1Output: 1Explanation:Choose the substring S[0, 1] a
15+ min read
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'nd substring. Examples: Input : "11235813" Output : ["1", "1", "2", "3", "5", "8", "13"] Input : "1111223" Output : ["1", "11", "12", "23"] Input : "1111213" Output : ["11", "1", "12", "13"] Input : "11121114" Output : []Iterate through the given string by pickin
9 min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First occurrence of Y(= "abc"): No of occurrences of X(=
6 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
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
Count of Subarray with B times Sum equal to C times Length
Given, an array A[] of N integers, and also given two positive integers B and C, the task is to find the number of subarrays, such that B* Sum of elements of the subarray = C * Length of the subarray (here * describes multiplication). Examples: Input: N = 3, A[] = {3, -1, 1}, B = 1, C = 1Output: 3Explanation: The subarrays satisfying the conditions
7 min read
Longest Substring of A that can be changed to Substring of B in at most T cost
Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. Note: If multiple valid substrings are possible then
13 min read
Count numbers which can be represented as sum of same parity primes
Given an arr[] of positive integers you have to count how many numbers can be represented as sum of same parity prime numbers(can be same) Examples: Input : arr[] = {1, 3, 4, 6}Output : 2Explanation: 4 = 2+2, 6 = 3+3 Input : arr[] = {4, 98, 0, 36, 51}Output : 3 1. If two numbers of same parity are added then they would be always even, so all odd nu
4 min read
Check if N can be represented as sum of integers chosen from set {A, B}
Given three integers N, A and B, the task is to find whether N can be represented as sum of A's and B's. Examples: Input: N = 11, A = 2, B = 3 Output: Yes 2 + 2 + 2 + 2 + 3 = 11 Input: N = 8, A = 3, B = 7 Output: No Approach: An efficient solution is to call a recursive function starting with zero (because zero is always possible). If function call
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg