Find two non-intersecting subarrays having equal sum of all elements raised to the power of 2
Last Updated :
29 Nov, 2021
Given an array arr[] of positive integers of size N, the task is to check if there exists two non-intersecting subarrays in arr[] such that sum of all possible 2(subarr[i]) and the sum of all possible 2(subarr2[j]) are equal.
Examples:
Input: arr[] = {4, 3, 0, 1, 2, 0}
Output: YES
Explanation: Expressing every array element in the form of 2arr[i], the array is modified to { 16, 8, 1, 2, 4, 1 }.
Therefore, two valid subarrays are { 16 } and { 8, 1, 2, 4, 1 } whose sum are equal.
Input: arr[]={ 3, 4 }
Output: NO
Approach: Since binary representation of all powers of 2 is unique, two such subarrays can only be obtained if any repeating element is present in that array. Otherwise, it is not possible.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findSubarrays( int arr[], int N)
{
sort(arr, arr + N);
int i = 0;
for (i = 0; i < N - 1; i++) {
if (arr[i] == arr[i + 1]) {
cout << "YES" << endl;
return ;
}
}
cout << "NO" << endl;
}
int main()
{
int arr[] = { 4, 3, 0, 1, 2, 0 };
int N = sizeof (arr) / sizeof (arr[0]);
findSubarrays(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findSubarrays( int arr[], int N)
{
Arrays.sort(arr);
int i = 0 ;
for (i = 0 ; i < N - 1 ; i++)
{
if (arr[i] == arr[i + 1 ])
{
System.out.println( "YES" );
return ;
}
}
System.out.println( "NO" );
}
public static void main(String[] args)
{
int [] arr = { 4 , 3 , 0 , 1 , 2 , 0 };
int N = arr.length;
findSubarrays(arr, N);
}
}
|
Python3
def findSubarrays(arr, N):
arr.sort();
i = 0 ;
for i in range (N - 1 ):
if (arr[i] = = arr[i + 1 ]):
print ( "YES" );
return ;
print ( "NO" );
if __name__ = = '__main__' :
arr = [ 4 , 3 , 0 , 1 , 2 , 0 ];
N = len (arr);
findSubarrays(arr, N);
|
C#
using System;
class GFG{
static void findSubarrays( int [] arr, int N)
{
Array.Sort(arr);
int i = 0;
for (i = 0; i < N - 1; i++)
{
if (arr[i] == arr[i + 1])
{
Console.WriteLine( "YES" );
return ;
}
}
Console.WriteLine( "NO" );
}
public static void Main()
{
int [] arr = { 4, 3, 0, 1, 2, 0 };
int N = arr.Length;
findSubarrays(arr, N);
}
}
|
Javascript
<script>
function findSubarrays(arr , N) {
arr.sort();
var i = 0;
for (i = 0; i < N - 1; i++) {
if (arr[i] == arr[i + 1]) {
document.write( "YES" );
return ;
}
}
document.write( "NO" );
}
var arr = [ 4, 3, 0, 1, 2, 0 ];
var N = arr.length;
findSubarrays(arr, N);
</script>
|
Time Complexity: O(NLogN)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...