The Wayback Machine - https://web.archive.org/web/20240708054314/https://www.geeksforgeeks.org/check-if-a-string-can-be-repeated-to-make-another-string/
Open In App

Check if a string can be repeated to make another string

Last Updated : 16 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1.

Examples: 

Input: a = “geeks”, b = “geeksgeeks” 
Output: 2 
“geeks” can be repeated twice to generate “geeksgeeks”

Input: a = “df”, b = “dfgrt” 
Output: -1 

Approach: 

  • If len(b) % len(a) != 0 then print -1 as b cannot be generated by repeating a.
  • Else set count = len(b) / len(a) and repeat a count number of times. 
    • If a = b then print count.
    • Else print -1.

Below is the implementation of the above approach: 

C++




// CPP implementation of the approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to return the count of repetitions
// of string a to generate string b
int getCount(string a, string b)
{
 
    // If b cannot be generated by repeating a
    if(b.length() % a.length() != 0)
        return -1;
     
    int count = b.length() /a.length();
 
    // Repeat a count number of times
    string str = "";
    for(int i = 0; i < count; i++)
    {
        str = str + a;
    }
    if(str == b)
        return count;
     
    return -1;
}
 
// Driver code
int main()
{
    string a = "geeks";
    string b = "geeksgeeks";
    cout << (getCount(a, b));
    return 0;
}
 
// This code is contributed by
// Surendra_Gangwar


Java




// Java implementation of the approach
 
class GfG
{
 
    // Function to return the count of repetitions
    // of string a to generate string b
    static int getCount(String a, String b)
    {
        // If b cannot be generated by repeating a
        if(b.length() % a.length() != 0)
            return -1;
         
        int count = b.length() / a.length();
     
        // Repeat a count number of times
        String str = "";
        for(int i = 0; i < count; i++)
        {
            str = str + a;
        }
         
        if(str.equals(b))
            return count;
         
        return -1;
    }
 
    // Driver code
    public static void main(String []args)
    {
        String a = "geeks";
        String b = "geeksgeeks";
        System.out.println(getCount(a, b));
    }
}
     
// This code is contributed by Rituraj Jain


Python 3




# Python3 implementation of the approach
 
# Function to return the count of repetitions
# of string a to generate string b
def getCount(a, b):
     
    # If b cannot be generated by repeating a
    if(len(b) % len(a) != 0):
        return -1;
     
    count = int(len(b) / len(a))
     
    # Repeat a count number of times
    a = a * count
     
    if(a == b):
        return count
     
    return -1;
 
# Driver code
if __name__ == '__main__':
    a = 'geeks'
    b = 'geeksgeeks'
    print(getCount(a, b))


C#




// C# implementation of the approach
using System;
 
class GfG
{
 
    // Function to return the count of repetitions
    // of string a to generate string b
    static int getCount(String a, String b)
    {
        // If b cannot be generated by repeating a
        if(b.Length % a.Length != 0)
            return -1;
         
        int count = b.Length / a.Length;
     
        // Repeat a count number of times
        String str = "";
        for(int i = 0; i < count; i++)
        {
            str = str + a;
        }
         
        if(str.Equals(b))
            return count;
         
        return -1;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        String a = "geeks";
        String b = "geeksgeeks";
        Console.WriteLine(getCount(a, b));
    }
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
 
// Javascript implementation of the approach
 
 
    // Function to return the count of repetitions
    // of string a to generate string b
    function getCount( a,  b) {
        // If b cannot be generated by repeating a
        if (b.length % a.length != 0)
            return -1;
 
        var count = parseInt(b.length / a.length);
 
        // Repeat a count number of times
        var str = "";
        for (i = 0; i < count; i++) {
            str = str + a;
        }
 
        if (str == (b))
            return count;
 
        return -1;
    }
 
    // Driver code
     
        var a = "geeks";
        var b = "geeksgeeks";
        document.write(getCount(a, b));
 
// This code is contributed by todaysgaurav
 
</script>


PHP




<?php
// PHP implementation of the approach
 
// Function to return the count of repetitions
// of string a to generate string b
function getCount($a, $b)
{
     
    // If b cannot be generated by repeating a
    if(strlen($b) % strlen($a) != 0)
        return -1;
     
    $count = floor(strlen($b) / strlen($a));
     
    // Repeat a count number of times
    // Repeat a count number of times
    $str = "";
    for($i = 0; $i < $count; $i++)
    {
        $str = $str . $a ;
    }
     
    if(strcmp($a,$b))
        return $count;
     
    return -1;
}
 
// Driver code
$a = 'geeks';
$b = 'geeksgeeks';
echo getCount($a, $b);
 
// This code is contributed by Ryuga
?>


Output

2







Time Complexity: O(n/m), where m and n are the lengths of the given strings a and b respectively.
Auxiliary Space: O(n), where n is the length of the string.

Approach:

  • Check if the length of string b is a multiple of the length of string a. If not, return -1.
  • Calculate the number of repetitions of a needed to generate b.
  • Create an empty stack.
  • Push each substring of length n (i.e., the length of a) from b onto the stack. This is done by iterating from 0 to the number of repetitions needed, and calling the substr() function on b with the starting index i*n and length n.
  • Pop each substring from the stack and append it to a new string str. This is done by iterating until the stack is empty, calling the top() function to get the top element of the stack, concatenating it to str, and then calling the pop() function to remove the top element.
  • Check if str is equal to b. If it is, return the number of repetitions calculated in step 2; otherwise, return -1.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <stack>
using namespace std;
 
int count_repetitions(string a, string b) {
    int n = a.length();
    int m = b.length();
    if (m % n != 0) {
        return -1;
    }
    int repetitions = m / n;
    stack<string> s;
    for (int i = 0; i < repetitions; i++) {
        s.push(b.substr(i*n, n));
    }
    string str = "";
    while (!s.empty()) {
        str += s.top();
        s.pop();
    }
    if (str == b) {
        return repetitions;
    } else {
        return -1;
    }
}
 
int main() {
    string a = "geeks";
    string b = "geeksgeeks";
    cout <<  count_repetitions(a, b) << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        String a = "geeks";
        String b = "geeksgeeks";
        System.out.println(countRepetitions(a, b));
    }
 
    // Function to count the number of times string 'a' is repeated to form string 'b'
    public static int countRepetitions(String a, String b) {
        int n = a.length();
        int m = b.length();
 
        // If the length of string 'b' is not a multiple of the length of string 'a', it's not possible to repeat 'a' to form 'b'
        if (m % n != 0) {
            return -1;
        }
 
        // Calculate the number of repetitions required to form 'b' from 'a'
        int repetitions = m / n;
 
        // Use a stack to store the individual substrings of 'b' that correspond to each repetition of 'a'
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < repetitions; i++) {
            // Push each substring into the stack by extracting it from 'b'
            stack.push(b.substring(i * n, (i + 1) * n));
        }
 
        // Build a new string by popping the substrings from the stack in reverse order
        StringBuilder str = new StringBuilder();
        while (!stack.isEmpty()) {
            str.append(stack.pop());
        }
 
        // If the final concatenated string matches 'b', it means 'a' is repeated 'repetitions' times to form 'b'
        // Return the number of repetitions, else return -1
        if (str.toString().equals(b)) {
            return repetitions;
        } else {
            return -1;
        }
    }
}


Python3




def count_repetitions(a, b):
    n = len(a)
    m = len(b)
 
    # Check if the length of 'b' is a multiple of the length of 'a'
    if m % n != 0:
        return -1
 
    repetitions = m // n
    stack = []
 
    # Split 'b' into 'repetitions' parts and store them in the stack
    for i in range(repetitions):
        stack.append(b[i * n: (i + 1) * n])
 
    str_result = ""
 
    # Pop elements from the stack and append them to 'str_result'
    while stack:
        str_result += stack.pop()
 
    # Compare 'str_result' with 'b' to check if they are the same
    if str_result == b:
        return repetitions
    else:
        return -1
 
 
if __name__ == "__main__":
    a = "geeks"
    b = "geeksgeeks"
    print(count_repetitions(a, b))
 
 
# This code is contributed by shivamgupta0987654321


C#




using System;
 
public class GFG
{
    // Function to count repetitions of 'a' in 'b'
    public static int CountRepetitions(string a, string b)
    {
        int n = a.Length;
        int m = b.Length;
 
        // Check if the length of 'b' is a multiple of the length of 'a'
        if (m % n != 0)
        {
            return -1;
        }
 
        int repetitions = m / n;
        var stack = new System.Collections.Generic.Stack<string>();
 
        // Split 'b' into 'repetitions' parts and store them in the stack
        for (int i = 0; i < repetitions; i++)
        {
            stack.Push(b.Substring(i * n, n));
        }
 
        string strResult = "";
 
        // Pop elements from the stack and append them to 'strResult'
        while (stack.Count > 0)
        {
            strResult += stack.Pop();
        }
 
        // Compare 'strResult' with 'b' to check if they are the same
        if (strResult == b)
        {
            return repetitions;
        }
        else
        {
            return -1;
        }
    }
 
    public static void Main(string[] args)
    {
        string a = "geeks";
        string b = "geeksgeeks";
        Console.WriteLine(CountRepetitions(a, b));
    }
}
// This code is contributed by rambabuguphka


Javascript




function countRepetitions(a, b) {
    const n = a.length;
    const m = b.length;
 
    // Check if the length of 'b' is a multiple of the length of 'a'
    if (m % n !== 0) {
        return -1;
    }
 
    const repetitions = m / n;
    const stack = [];
 
    // Split 'b' into 'repetitions' parts and store them in the stack
    for (let i = 0; i < repetitions; i++) {
        stack.push(b.substring(i * n, (i + 1) * n));
    }
 
    let strResult = "";
 
    // Pop elements from the stack and append them to 'strResult'
    while (stack.length > 0) {
        strResult += stack.pop();
    }
 
    // Compare 'strResult' with 'b' to check if they are the same
    if (strResult === b) {
        return repetitions;
    } else {
        return -1;
    }
}
 
const a = "geeks";
const b = "geeksgeeks";
console.log(countRepetitions(a, b));
 
// This code is contributed by shivamgupta0987654321


Output

2








Time Complexity: O(m), where m is the length of the string b.

Auxiliary Space: O(m/n + m), where n is the length of the string a and m is the length of the string b.



Similar Reads

Check if string S1 can be formed using repeated insertions of another string S2
Given two strings S1 and S2 consisting of unique characters, the task is to check S1 can be formed by repeated insertions of string S2. Input: S1 = "aabb", S2 = "ab"Output: YesExplanation: the mentioned string can be obtained after series of moves: Insert string "ab" in an empty string. Current string will be "ab"insert "ab" after "a". The final st
7 min read
Check if end of a sorted Array can be reached by repeated jumps of one more, one less or same number of indices as previous jump
Given a sorted array arr[] of size N, the task is to check if it is possible to reach the end of the given array from arr[1] by jumping either arr[i] + k - 1, arr[i] + k, or arr[i] + k + 1 in each move, where k represents the number of indices jumped in the previous move. Consider K = 1 initially. If it is possible, then print "Yes". Otherwise, pri
11 min read
Check if a string can be formed from another string using given constraints
Given two strings S1 and S2(all characters are in lower-case). The task is to check if S2 can be formed from S1 using given constraints: 1. Characters of S2 is there in S1 if there are two 'a' in S2, then S1 should have two 'a' also. 2. If any character of S2 is not present in S1, check if the previous two ASCII characters are there in S1. e.g., if
7 min read
Check if a string can be converted to another string by replacing vowels and consonants
Given two strings S1 and S2, you are allowed only to change a character at any position to any vowel if it is a vowel or to a consonant, if it is a consonant. The task is to check if a string S1 can be changed to S2 or S2 can be changed to S1. Examples: Input: S1 = "abcgle", S2 = "ezggli" Output: Yes Change 'a' to 'e', 'b' to 'z', 'c' to 'g' and 'e
6 min read
Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
9 min read
Check if a string can be obtained by appending subsequences of another string
Given two strings str1 and str2 of lengths N and M respectively, the task is to check if str2 can be formed by appending subsequences of str1 multiple times. If possible, print the minimum number of append operations required. Otherwise, print -1. Examples: Input: str1 = "abb", str2 = "ababbbbb"Output: 4Explanation:String str2 can be formed by appe
8 min read
Check if a string can be made equal to another string by swapping or replacement of characters
Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = “abc”, S2 = “bca”Output: YesExplanation:Operation 1: "abc" -
8 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
Python3 Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Javascript Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
three90RightbarBannerImg