Check if a string can be repeated to make another string
Last Updated :
07 May, 2025
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
# 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
?>
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;
}
}
}
Python
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
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 stri
7 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 Explana
7 min read
Check if a string is a scrambled form of another string Given two strings s1 and s2 of equal length, the task is to determine if s2 is a scrambled version of s1.A scrambled string is formed by recursively splitting the string into two non-empty substrings and rearranging them randomly (s = x + y or s = y + x) and then recursively scramble the two substri
15+ min read
Javascript Program To Check If A String Is Substring Of Another Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
2 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"Outp
8 min read