Longest alternating (positive and negative) subarray starting at every index
Last Updated :
02 Aug, 2022
A subarray is called alternating if any two consecutive numbers in it have opposite signs (i.e. one of them should be negative, whereas the other should be positive).
Given an array of n integers. For each index i, we need to find the length if the longest alternating subarray starting at i.
Examples:
Input : a[] = {1, -5, 1, -5}
Output : For index 0, {1, -5, 1, -5} = 4
index 1, {-5, 1, -5} = 3
index 2, {1, -5} = 2
index 3, {-5} = 1.
Input :a[] = {-5, -1, -1, 2, -2, -3}
Output : index 0 = 1,
index 1 = 1,
index 2 = 3,
index 3 = 2,
index 4 = 1,
index 5 = 1,
Naive Approach: As per the problem statement we need to find the longest alternating subarray prefix length for every index . So one of the naive way is to start from all the indices i ( i.e., 0 to N-1) and calculate the length of the longest alternating subarray length . While traversing at any point of time if we observe two adjacent elements having the same sign (i.e., either positive or negative ) we need not to proceed further we can break the loop and update the length till the computed index .
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
void computeLength(vector< long > &arr, long n)
{
for ( long i=0;i<n;i++)
{
long j=i;
while (j < n-1)
{
if ((arr[j] >= 0 and arr[j+1] >= 0) or (arr[j] < 0 and arr[j+1] < 0))
break ;
j++;
}
cout << abs (j - i) + 1 << " " ;
}
return ;
}
int main()
{
long n;
cin >> n;
vector< long > arr(n,0);
for ( long i=0;i<n;i++)
{
cin >> arr[i];
}
computeLength(arr,n);
cout << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static void computeLength( long [] arr, long n)
{
for ( long i = 0 ; i < n; i++)
{
long j=i;
while (j < n- 1 )
{
if ((arr[( int )j] >= 0 && arr[( int )j+ 1 ] >= 0 ) || (arr[( int )j] < 0 && arr[( int )j+ 1 ] < 0 ))
break ;
j++;
}
System.out.printf( "%d " ,Math.abs(j - i) + 1 );
}
return ;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long [] arr = new long [( int )n];
for ( long i= 0 ;i<n;i++)
{
arr[( int )i] = sc.nextLong();
}
computeLength(arr,n);
System.out.println();
}
}
|
Python3
def computeLength(arr, n):
for i in range (n):
j = i
while (j < n - 1 ):
if ((arr[j] > = 0 and arr[j + 1 ] > = 0 ) or (arr[j] < 0 and arr[j + 1 ] < 0 )):
break
j + = 1
print ( abs (j - i) + 1 ,end = " " )
return
n = int ( input ())
arr = [ 0 for i in range (n)]
for i in range (n):
arr[i] = int ( input ())
computeLength(arr,n)
print ()
|
C#
using System;
public class GFG {
static void computeLength( long [] arr, long n)
{
for ( long i = 0; i < n; i++) {
long j = i;
while (j < n - 1) {
if ((arr[( int )j] >= 0
&& arr[( int )j + 1] >= 0)
|| (arr[( int )j] < 0
&& arr[( int )j + 1] < 0))
break ;
j++;
}
Console.Write(Math.Abs(j - i) + 1 + " " );
}
return ;
}
static public void Main()
{
long n = Convert.ToInt64(Console.ReadLine());
long [] arr = new long [( int )n];
for ( long i = 0; i < n; i++) {
arr[( int )i]
= Convert.ToInt64(Console.ReadLine());
}
computeLength(arr, n);
}
}
|
Javascript
<script>
function computeLength(arr, n)
{
for (let i = 0; i < n; i++)
{
let j = i;
while (j < n - 1)
{
if ((arr[j] >= 0 && arr[j+1] >= 0) || (arr[j] < 0 && arr[j+1] < 0))
break ;
j++;
}
document.write(Math.abs(j - i) + 1, " " );
}
return ;
}
let n = prompt();
let arr = new Array(n).fill(0);
for (let i = 0; i < n; i++)
{
arr[i] = prompt();
}
computeLength(arr, n);
document.write( "</br>" );
</script>
|
Input :
6
-5 -1 -1 2 -2 -3
Output :
1 1 3 2 1 1
Time Complexity : O(N^2) .
- For the arrays like [ 1 , -1 , 2 , -1] we will be traversing until the end of the array for each index so the complexity will look like :
- Let us take for a value of N .
- In each iteration we traverse N – i -1 indices where i [ 0, N-1] . So that sums N-1 + N -2 + N – 3 + …. + 1 . This is the sum of N-1 natural numbers the mathematical notation is (N * (N – 1))/2 . If we simplify it further :
- (N^2 – N)/2
- When we are trying to represent the above term in the form of asymptotic notations , we need to drop all the lower terms as well as the coefficients . So the higher term is N ^ 2 , hence it can be represented as O ( N ^ 2) .
Space Complexity : O(1). Since apart from the input array we didn’t use any auxiliary data structures to perform any computations .
Efficient Approach: Observe that when a[i] and a[i+1] have opposite signs, count[i] will be 1 more than count[i+1]. Otherwise when they have same sign count[i] will be 1.
We use Dynamic Programming here.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void longestAlternating( int arr[], int n)
{
int count[n];
count[n - 1] = 1;
for ( int i = n - 2; i >= 0; i--) {
if (arr[i] * arr[i + 1] < 0)
count[i] = count[i + 1] + 1;
else
count[i] = 1;
}
for ( int i = 0; i < n; i++)
cout << count[i] << " " ;
}
int main()
{
int a[] = { -5, -1, -1, 2, -2, -3 };
int n = sizeof (a) / sizeof (a[0]);
longestAlternating(a, n);
return 0;
}
|
Java
import java.util.*;
class Longest{
public static void longestAlternating( int arr[],
int n)
{
int [] count = new int [n];
count[n - 1 ] = 1 ;
for ( int i = n - 2 ; i >= 0 ; i--) {
if (arr[i] * arr[i + 1 ] < 0 )
count[i] = count[i + 1 ] + 1 ;
else
count[i] = 1 ;
}
for ( int i = 0 ; i < n; i++)
System.out.print(count[i] + " " );
}
public static void main(String[] args)
{
int a[] = { - 5 , - 1 , - 1 , 2 , - 2 , - 3 };
int n = 6 ;
longestAlternating(a, n);
}
}
|
Python3
def longestAlternating(arr, n) :
count = [ None ] * n
count[n - 1 ] = 1
i = n - 2
while i > = 0 :
if (arr[i] * arr[i + 1 ] < 0 ) :
count[i] = count[i + 1 ] + 1
else :
count[i] = 1 ;
i = i - 1
i = 0
while i < n :
print (count[i], end = " " )
i = i + 1
a = [ - 5 , - 1 , - 1 , 2 , - 2 , - 3 ]
n = len (a)
longestAlternating(a, n);
|
C#
using System;
class Longest
{
public static void longestAlternating( int []arr,
int n)
{
int [] count = new int [n];
count[n - 1] = 1;
for ( int i = n - 2; i >= 0; i--)
{
if (arr[i] * arr[i + 1] < 0)
count[i] = count[i + 1] + 1;
else
count[i] = 1;
}
for ( int i = 0; i < n; i++)
Console.Write(count[i] + " " );
}
public static void Main()
{
int []a = { -5, -1, -1, 2, -2, -3 };
int n = 6;
longestAlternating(a, n);
}
}
|
PHP
<?php
function longestAlternating( $arr , $n )
{
$count = array ();
$count [ $n - 1] = 1;
for ( $i = $n - 2; $i >= 0; $i --)
{
if ( $arr [ $i ] * $arr [ $i + 1] < 0)
$count [ $i ] = $count [ $i + 1] + 1;
else
$count [ $i ] = 1;
}
for ( $i = 0; $i < $n ; $i ++)
echo $count [ $i ] , " " ;
}
$a = array ( -5, -1, -1, 2, -2, -3 );
$n = count ( $a );
longestAlternating( $a , $n );
?>
|
Javascript
<script>
function longestAlternating(arr, n)
{
let count = new Array(n);
count[n - 1] = 1;
for (let i = n - 2; i >= 0; i--) {
if (arr[i] * arr[i + 1] < 0)
count[i] = count[i + 1] + 1;
else
count[i] = 1;
}
for (let i = 0; i < n; i++)
document.write(count[i] + " " );
}
let a = [ -5, -1, -1, 2, -2, -3 ];
let n = a.length;
longestAlternating(a, n);
</script>
|
Time Complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(N), where N represents the size of the given array.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...