Given an array containing only 0s and 1s. For each index ‘i‘(0 index), find length of the longest alternating sub-array starting from ‘i‘ to ‘j‘ i.e., ai..j for i <= j < n. Alternating sub-array means that any two adjacent elements should be different.
Example:
Input: arr[] = {1, 0, 1, 0, 0, 1}
Output: 4 3 2 1 2 1
Explanation
Length for index '0': {1 0 1 0} => 4
Length for index '1': {0 1 0} => 3
Length for index '2': {1 0} => 2
Length for index '3': {0} => 1
Length for index '4': {0 1} => 2
Length for index '5': {1} => 1
Simple approach is to iterate for every index by using two ‘for loops’ for finding the length of each index. The outer loop picks a starting point ‘i’ and the inner loop considers all sub-arrays starting from ‘i’. Time complexity of this approach is O(n2) which is not sufficient for large value of ‘n’.
Better approach is to use Dynamic programming. First of all, let’s see how to check for alternating sub-array. To check whether two elements are alternating or not, we can simply take XOR(Ex-OR) of both of them and then compare with ‘0’ and ‘1’.
- If there XOR is ‘0’, that means both numbers are not alternating(equal elements).
- If there XOR is ‘1’, that means both are alternating(different elements)
Let len[i] denotes length of an alternating sub-array starting at position ‘i’. If arr[i] and arr[i+1] have different values, then len[i] will be one more than len[i+1]. Otherwise if they are same elements, len[i] will be just 1.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void alternateSubarray( bool arr[], int n)
{
int len[n];
len[n - 1] = 1;
for ( int i = n - 2; i >= 0; --i) {
if (arr[i] ^ arr[i + 1] == 1)
len[i] = len[i + 1] + 1;
else
len[i] = 1;
}
for ( int i = 0; i < n; ++i)
cout << len[i] << " " ;
}
int main()
{
bool arr[] = { 1, 0, 1, 0, 0, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
alternateSubarray(arr, n);
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
static void alternateSubarray( boolean arr[], int n)
{
int len[] = new int [n];
len[n - 1 ] = 1 ;
for ( int i = n - 2 ; i >= 0 ; --i) {
if (arr[i] ^ arr[i + 1 ] == true )
len[i] = len[i + 1 ] + 1 ;
else
len[i] = 1 ;
}
for ( int i = 0 ; i < n; ++i)
System.out.print(len[i] + " " );
}
public static void main(String[] args)
{
boolean arr[] = { true , false , true , false , false , true };
int n = arr.length;
alternateSubarray(arr, n);
}
}
|
Python3
def alternateSubarray(arr,n):
len = []
for i in range (n + 1 ):
len .append( 0 )
len [n - 1 ] = 1
for i in range (n - 2 , - 1 , - 1 ):
if (arr[i] ^ arr[i + 1 ] = = True ):
len [i] = len [i + 1 ] + 1
else :
len [i] = 1
for i in range (n):
print ( len [i] , " " ,end = "")
arr = [ True , False , True , False , False , True ]
n = len (arr)
alternateSubarray(arr, n)
|
C#
using System;
class GFG {
static void alternateSubarray( bool []arr,
int n)
{
int []len = new int [n];
len[n - 1] = 1;
for ( int i = n - 2; i >= 0; --i)
{
if (arr[i] ^ arr[i + 1] == true )
len[i] = len[i + 1] + 1;
else
len[i] = 1;
}
for ( int i = 0; i < n; ++i)
Console.Write(len[i] + " " );
}
public static void Main()
{
bool []arr = { true , false , true ,
false , false , true };
int n = arr.Length;
alternateSubarray(arr, n);
}
}
|
PHP
<?php
function alternateSubarray(& $arr , $n )
{
$len = array_fill (0, $n , NULL);
$len [ $n - 1] = 1;
for ( $i = $n - 2; $i >= 0; -- $i )
{
if ( $arr [ $i ] ^ $arr [ $i + 1] == 1)
$len [ $i ] = $len [ $i + 1] + 1;
else
$len [ $i ] = 1;
}
for ( $i = 0; $i < $n ; ++ $i )
echo $len [ $i ] . " " ;
}
$arr = array (1, 0, 1, 0, 0, 1);
$n = sizeof( $arr );
alternateSubarray( $arr , $n );
?>
|
Javascript
<script>
function alternateSubarray(arr, n)
{
let len = new Array(n);
len[n - 1] = 1;
for (let i = n - 2; i >= 0; --i)
{
if (arr[i] ^ arr[i + 1] == 1)
len[i] = len[i + 1] + 1;
else
len[i] = 1;
}
for (let i = 0; i < n; ++i)
document.write(len[i] + " " );
}
let arr = [ 1, 0, 1, 0, 0, 1 ];
let n = arr.length;
alternateSubarray(arr, n);
</script>
|
Time complexity: O(n)
Auxiliary space: O(n)
Another Efficient approach is, instead of storing all the sub-array elements in len[] array, we can directly print it until mismatch(equal adjacent elements) is found. When a mismatch is found, we print count from current value to 0.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void alternateSubarray( bool arr[], int n)
{
int count = 1;
int prev = arr[0];
for ( int i = 1; i < n; ++i) {
if ((arr[i] ^ prev) == 0)
{
while (count)
cout << count-- << " " ;
}
++count;
prev = arr[i];
}
while (count)
cout << count-- << " " ;
}
int main()
{
bool arr[] = { 1, 0, 1, 0, 0, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
alternateSubarray(arr, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void alternateSubarray( boolean arr[], int n)
{
int count = 1 ;
boolean prev = arr[ 0 ];
for ( int i = 1 ; i < n; ++i) {
if ((arr[i] ^ prev) == false ) {
while (count > 0 ) {
System.out.print(count-- + " " );
}
}
++count;
prev = arr[i];
}
while (count != 0 ) {
System.out.print(count-- + " " );
}
}
public static void main(String args[])
{
boolean arr[]
= { true , false , true , false , false , true };
int n = arr.length;
alternateSubarray(arr, n);
}
}
|
Python3
def alternateSubarray(arr, n):
count = 1
prev = arr[ 0 ]
for i in range ( 1 , n):
if ((arr[i] ^ prev) = = 0 ):
while (count):
print (count, end = " " )
count - = 1
count + = 1
prev = arr[i]
while (count):
print (count, end = " " )
count - = 1
if __name__ = = '__main__' :
arr = [ 1 , 0 , 1 , 0 , 0 , 1 ]
n = len (arr)
alternateSubarray(arr, n)
|
C#
using System;
public class Test{
static void alternateSubarray( bool []arr, int n) {
int count = 1;
bool prev = arr[0];
for ( int i = 1; i < n; ++i) {
if ((arr[i] ^ prev) == false ) {
while (count > 0) {
Console.Write(count-- + " " );
}
}
++count;
prev = arr[i];
}
while (count != 0) {
Console.Write(count-- + " " );
}
}
public static void Main() {
bool []arr = { true , false , true , false , false , true };
int n = arr.Length;
alternateSubarray(arr, n);
}
}
|
PHP
<?php
function alternateSubarray( $arr , $n )
{
$count = 1;
$prev = $arr [0];
for ( $i = 1; $i < $n ; ++ $i )
{
if (( $arr [ $i ] ^ $prev ) == 0)
{
while ( $count )
echo $count -- , " " ;
}
++ $count ;
$prev = $arr [ $i ];
}
while ( $count )
echo $count -- , " " ;
}
$arr = array (1, 0, 1, 0, 0, 1);
$n = sizeof( $arr ) ;
alternateSubarray( $arr , $n );
?>
|
Javascript
<script>
function alternateSubarray(arr, n)
{
let count = 1;
let prev = arr[0];
for (let i = 1; i < n; ++i)
{
if ((arr[i] ^ prev) == false )
{
while (count > 0)
{
document.write(count-- + " " );
}
}
++count;
prev = arr[i];
}
while (count != 0)
{
document.write(count-- + " " );
}
}
let arr = [ true , false , true , false , false , true ];
let n = arr.length;
alternateSubarray(arr, n);
</script>
|
Time complexity: O(n)
Auxiliary space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Sep, 2023
Like Article
Save Article