Given a string str, the task is to check whether the given string is made up of only two alternating characters.
Examples:
Input: str = “ABABABAB”
Output: Yes
Input: str = “XYZ”
Output: No
Approach: In order for the string to be made up of only two alternating characters, it must satisfy the following conditions:
- All the characters at odd indices must be same.
- All the characters at even indices must be same.
- str[0] != str[1] (This is because string of type “AAAAA” where a single character is repeated a number of time will also satisfy the above two conditions)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isTwoAlter(string s)
{
for ( int i = 0; i < s.length() - 2; i++) {
if (s[i] != s[i + 2]) {
return false ;
}
}
if (s[0] == s[1])
return false ;
return true ;
}
int main()
{
string str = "ABAB" ;
if (isTwoAlter(str))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static boolean isTwoAlter(String s)
{
for ( int i = 0 ; i < s.length() - 2 ; i++)
{
if (s.charAt(i) != s.charAt(i + 2 ))
{
return false ;
}
}
if (s.charAt( 0 ) == s.charAt( 1 ))
return false ;
return true ;
}
public static void main (String[] args)
{
String str = "ABAB" ;
if (isTwoAlter(str))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python 3
def isTwoAlter( s):
for i in range ( len ( s) - 2 ) :
if (s[i] ! = s[i + 2 ]) :
return False
if (s[ 0 ] = = s[ 1 ]):
return False
return True
if __name__ = = "__main__" :
str = "ABAB"
if (isTwoAlter( str )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isTwoAlter( string s)
{
for ( int i = 0; i < s.Length - 2; i++)
{
if (s[i] != s[i +2])
{
return false ;
}
}
if (s[0] == s[1])
return false ;
return true ;
}
public static void Main()
{
string str = "ABAB" ;
if (isTwoAlter(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isTwoAlter(s)
{
for (let i = 0; i < s.length - 2; i++)
{
if (s[i] != s[i+2])
{
return false ;
}
}
if (s[0] == s[1])
return false ;
return true ;
}
let str = "ABAB" ;
if (isTwoAlter(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity : O(N)
Auxiliary Space : O(1)
Using two characters to check alternating pattern:
Approach:
Check if the length of the given string is 1, then return False.
Assign the first character of the string to a variable called “first_char”.
Initialize an empty string variable called “second_char”.
Iterate over the string starting from the second character.
If the current character is not equal to the first character, check if “second_char” is empty, if it is, assign the current character to “second_char”, else if the current character is not equal to “second_char”, return False.
If the loop completes without returning False, return True.
C++
#include <iostream>
#include <string>
#include <chrono>
using namespace std;
bool is_alternating_string(string str) {
if (str.length() == 1) {
return false ;
}
char first_char = str[0];
char second_char = '\0' ;
for ( size_t i = 1; i < str.length(); i++) {
if (str[i] != first_char) {
if (second_char == '\0' ) {
second_char = str[i];
} else if (str[i] != second_char) {
return false ;
}
}
}
return true ;
}
int main() {
string input_str1 = "ABABABAB" ;
string input_str2 = "XYZ" ;
auto start_time = chrono::high_resolution_clock::now();
bool result1 = is_alternating_string(input_str1);
bool result2 = is_alternating_string(input_str2);
auto end_time = chrono::high_resolution_clock::now();
cout << "Input: str = " << input_str1 << ", Output: " << (result1 ? "Yes" : "No" ) << endl;
cout << "Input: str = " << input_str2 << ", Output: " << (result2 ? "Yes" : "No" ) << endl;
auto duration = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
double time_taken = duration.count() / 1000000.0;
cout << "Time taken: " << time_taken << " seconds" << endl;
return 0;
}
|
Python3
import time
def is_alternating_string( str ):
if len ( str ) = = 1 :
return False
first_char = str [ 0 ]
second_char = ""
for i in range ( 1 , len ( str )):
if str [i] ! = first_char:
if second_char = = "":
second_char = str [i]
elif str [i] ! = second_char:
return False
return True
input_str1 = "ABABABAB"
input_str2 = "XYZ"
start_time = time.time()
result1 = is_alternating_string(input_str1)
result2 = is_alternating_string(input_str2)
end_time = time.time()
print ( "Approach 1:" )
print ( "Input: str = " , input_str1, ", Output: " , "Yes" if result1 else "No" )
print ( "Input: str = " , input_str2, ", Output: " , "Yes" if result2 else "No" )
print ( "Time taken: " , end_time - start_time, " seconds" )
|
Javascript
function isAlternatingString(str) {
if (str.length === 1) {
return false ;
}
let firstChar = str[0];
let secondChar = "" ;
for (let i = 1; i < str.length; i++) {
if (str[i] !== firstChar) {
if (secondChar === "" ) {
secondChar = str[i];
} else if (str[i] !== secondChar) {
return false ;
}
}
}
return true ;
}
let inputStr1 = "ABABABAB" ;
let inputStr2 = "XYZ" ;
let startTime = Date.now();
let result1 = isAlternatingString(inputStr1);
let result2 = isAlternatingString(inputStr2);
let endTime = Date.now();
console.log( "Approach 1:" );
console.log( "Input: str =" , inputStr1, ", Output:" , result1 ? "Yes" : "No" );
console.log( "Input: str =" , inputStr2, ", Output:" , result2 ? "Yes" : "No" );
console.log( "Time taken:" , (endTime - startTime) / 1000, "seconds" );
|
OutputApproach 1:
Input: str = ABABABAB , Output: Yes
Input: str = XYZ , Output: No
Time taken: 5.245208740234375e-06 seconds
Time Complexity: O(n)
Auxiliary Space: O(1)