Check if Rotated Concatenated Strings are valid or not
Last Updated :
20 Dec, 2023
Given a string s formed by concatenating another string s1 to itself, followed by a rotation to the left any number of times, the task is to determine whether a given string s is valid, indicating whether it can be formed from the original string s1.
Examples:
Input: s = “abcabc”
Output: 1
Explanation: s1 = “abcabc” can be generated by s = “abc”. s+s without any rotations gives s1.
Input: s1 = “abccba”
Output: 0
Explanation: It is not possible to obtain any string s which can be converted into the given s1.
Approach: This can be solved with the following idea:
To string to be possible, it is always how many time we rotate characters present at i and i + mid, should be same. If not return false, otherwise true.
Below are the steps involved:
- Check whether the string is even in length or not.
- Iterate from 0 to mid:
- If s[i] != s[i + mid], return false.
- After iterating, return true.
Below is the implemntation of the code:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int isItPossible(string s)
{
if (s.length() % 2 != 0) {
return 0;
}
int mid = s.length() / 2;
int i = 0;
while (i < mid) {
if (s[i] != s[i + mid]) {
return 0;
}
i++;
}
return 1;
}
int main()
{
string s = "abcabc";
cout << isItPossible(s);
return 0;
}
|
Java
public class Main {
static int isItPossible(String s) {
if (s.length() % 2 != 0 ) {
return 0 ;
}
int mid = s.length() / 2 ;
int i = 0 ;
while (i < mid) {
if (s.charAt(i) != s.charAt(i + mid)) {
return 0 ;
}
i++;
}
return 1 ;
}
public static void main(String[] args) {
String s = "abcabc" ;
System.out.println(isItPossible(s));
}
}
|
Python3
def isItPossible(s):
if len (s) % 2 ! = 0 :
return 0
mid = len (s) / / 2
i = 0
while i < mid:
if s[i] ! = s[i + mid]:
return 0
i + = 1
return 1
s = "abcabc"
print (isItPossible(s))
|
C#
using System;
public class GFG {
static int IsItPossible( string s)
{
if (s.Length % 2 != 0) {
return 0;
}
int mid = s.Length / 2;
int i = 0;
while (i < mid) {
if (s[i] != s[i + mid]) {
return 0;
}
i++;
}
return 1;
}
static void Main()
{
string s = "abcabc" ;
Console.WriteLine(IsItPossible(s));
}
}
|
Javascript
function isItPossible(s) {
if (s.length % 2 !== 0) {
return 0;
}
const mid = s.length / 2;
let i = 0;
while (i < mid) {
if (s.charAt(i) !== s.charAt(i + mid)) {
return 0;
}
i++;
}
return 1;
}
const s = "abcabc" ;
console.log(isItPossible(s));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...