Check if there exist 4 indices in the array satisfying the given condition
Last Updated :
05 Dec, 2022
Given an array A[] of N positive integers and 3 integers X, Y, and Z, the task is to check if there exist 4 indices (say p, q, r, s) such that the following conditions are satisfied:
- 0 < p < q < r < s < N
- Sum of the subarray from A[p] to A[q - 1] is X
- Sum of the subarray from A[q] to A[r - 1] is Y
- Sum of the subarray from A[r] to A[s - 1] is Z
Examples:
Input: N = 10, A[] = {1, 3, 2, 2, 2, 3, 1, 4, 3, 2}, X = 5, Y = 7, Z = 5
Output: YES
Explanation: The 4 integers p, q, r, s are {1, 3, 6, 8}.
- A[1] + A[2] = 5
- A[3] + A [4] + A[5] = 7
- A[6] + A[7] = 5
Input: N = 9, A[] = {31, 41, 59, 26, 53, 58, 97, 93, 23}, X = 100, Y = 101, Z = 100
Output: NO
Approach: The problem can be solved easily with the help of cumulative sum and Binary search.
If we calculate the cumulative sum of the array, then the sum of any subarray can be computed in O(1). Say S[i] is cumulative sum till ith index, then S[j] - S[i] = A[i] + A[i + 1] + .... + A[j - 1].
So, given conditions can be converted into the following:
We need to find 4 integers p, q, r, s such that:
S[q] - S[p] = X
S[r] - S[q] = Y
S[s] - S[r] = Z
Now, for any fixed index (say p), we can find another index (say q) using binary search in a monotonically increasing array (cumulative sum), such that S[q] = S[p] + X. Similarly, we can find r and s. We can perform this search for all possible indices.
NOTE: A set can be used so that we won't need to perform a binary search explicitly each time.
Thus, the problem can be solved using the following steps :
- Declare a set (say S).
- Initialize a variable (say curr) by 0, to calculate the cumulative sum at each iteration.
- Iterate through the given array and insert the cumulative sum into the set.
- Iterate through the set and check if the current element of the set satisfies the given condition along with 3 other elements (which are also in the set). If so, return true.
- Else, return false.
Below is the implementation for the above approach:
C++
// C++ code based on the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if it is possible to
// find 4 integers satisfying the
// given condition
bool isPossible(int N, int A[], int X, int Y, int Z)
{
// Declaring a set
set<int> S({ 0 });
// Initializing variable to store
// cumulative sum
int curr = 0;
// Inserting cumulative sums
// into the set
for (int i = 0; i < N; i++) {
curr += A[i];
S.insert(curr);
}
// Iterating through the set
for (auto it : S) {
// If current element of set
// satisfies the given condition
// along with 3 other elements
// (which are also in set),
// return true
if (S.find(it + X) != S.end()
&& S.find(it + X + Y) != S.end()
&& S.find(it + X + Y + Z) != S.end()) {
return true;
}
}
// Return false if the iteration
// completes without getting
// the required elements
return false;
}
// Driver code
int main()
{
int N = 10, X = 5, Y = 7, Z = 5;
int A[] = { 1, 3, 2, 2, 2, 3, 1, 4, 3, 2 };
// Function call
int answer = isPossible(N, A, X, Y, Z);
if (answer == true) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
return 0;
}
Java
// Java code based on the above approach
import java.util.*;
class GFG{
// Function to check if it is possible to
// find 4 integers satisfying the
// given condition
static boolean isPossible(int N, int A[], int X, int Y, int Z)
{
// Declaring a set
HashSet<Integer> S = new HashSet<>();
// Initializing variable to store
// cumulative sum
int curr = 0;
// Inserting cumulative sums
// into the set
for (int i = 0; i < N; i++) {
curr += A[i];
S.add(curr);
}
// Iterating through the set
for (int it : S) {
// If current element of set
// satisfies the given condition
// along with 3 other elements
// (which are also in set),
// return true
if (!S.contains(it + X)
&& !S.contains(it + X + Y)
&& !S.contains(it + X + Y + Z) ) {
return true;
}
}
// Return false if the iteration
// completes without getting
// the required elements
return false;
}
// Driver code
public static void main(String[] args)
{
int N = 10, X = 5, Y = 7, Z = 5;
int A[] = { 1, 3, 2, 2, 2, 3, 1, 4, 3, 2 };
// Function call
boolean answer = isPossible(N, A, X, Y, Z);
if (answer == true) {
System.out.print("YES" +"\n");
}
else {
System.out.print("NO" +"\n");
}
}
}
// This code is contributed by shikhasingrajput
Python3
# Function to check if it is possible to
# find 4 integers satisfying the
# given condition
def isPossible(N, A, X, Y, Z) :
# Declaring a set
S = set()
# Initializing variable to store
# cumulative sum
curr = 0
# Inserting cumulative sums
# into the set
for i in range(N):
curr += A[i]
S.add(curr)
# Iterating through the set
for it in S:
# If current element of set
# satisfies the given condition
# along with 3 other elements
# (which are also in set),
# return true
if ((it + X) in S
and (it + X + Y) in S
and (it + X + Y + Z) in S) :
return True
# Return false if the iteration
# completes without getting
# the required elements
return False
# Driver code
if __name__ == "__main__":
N = 10
X = 5
Y = 7
Z = 5
A = [ 1, 3, 2, 2, 2, 3, 1, 4, 3, 2 ]
# Function call
answer = isPossible(N, A, X, Y, Z)
if (answer == True) :
print("YES" )
else :
print("NO")
# This code is contributed by code_hunt.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to check if it is possible to
// find 4 integers satisfying the
// given condition
static bool isPossible(int N, int[] A, int X, int Y, int Z)
{
// Declaring a set
HashSet<int> S = new HashSet<int>();
// Initializing variable to store
// cumulative sum
int curr = 0;
// Inserting cumulative sums
// into the set
for (int i = 0; i < N; i++) {
curr += A[i];
S.Add(curr);
}
// Iterating through the set
foreach (int it in S) {
// If current element of set
// satisfies the given condition
// along with 3 other elements
// (which are also in set),
// return true
if (!S.Contains(it + X)
&& !S.Contains(it + X + Y)
&& !S.Contains(it + X + Y + Z) ) {
return true;
}
}
// Return false if the iteration
// completes without getting
// the required elements
return false;
}
static public void Main ()
{
int N = 10, X = 5, Y = 7, Z = 5;
int[] A = { 1, 3, 2, 2, 2, 3, 1, 4, 3, 2 };
// Function call
bool answer = isPossible(N, A, X, Y, Z);
if (answer == true) {
Console.Write("YES" +"\n");
}
else {
Console.Write("NO" +"\n");
}
}
}
// This code is contributed by sanjoy_62.
JavaScript
// JavaScript code based on the above approach
// Function to check if it is possible to
// find 4 letters satisfying the
// given condition
function isPossible(N, A, X, Y, Z)
{
// Declaring a set
let S = new Set([0]);
// Initializing variable to store
// cumulative sum
let curr = 0;
// adding cumulative sums
// into the set
for (let i = 0; i < N; i++) {
curr += A[i];
S.add(curr);
}
// Iterating through the set
for (const it of S.values()) {
// If current element of set
// satisfies the given condition
// along with 3 other elements
// (which are also in set),
// return true
if (S.has(it + X) && S.has(it + X + Y) && S.has(it + X + Y + Z)) {
return true;
}
}
// Return false if the iteration
// completes without getting
// the required elements
return false;
}
// Driver code
let N = 10,
X = 5,
Y = 7,
Z = 5;
let A = [1, 3, 2, 2, 2, 3, 1, 4, 3, 2];
// Function call
let answer = isPossible(N, A, X, Y, Z);
if (answer == true) {
console.log("YES");
} else {
console.log("NO");
}
// This code is contributed by ishankhandelwals.
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Similar Reads
Check if there exists any subarray with the given conditions
Given two integers N and X. Then the task is to return YES or NO by checking whether there exists a subarray in any permutation of length N such that it contains a subarray, where A*B is equal to the X. Here A and B denote the number of elements in sub-array and the first element of sorted subarray
5 min read
Check if it is possible to construct an array with the given conditions
Given integers N and K and an array A[] of M integers. The task is to check if it is possible to construct an array of size N such that- All the K consecutive elements of the array are distinct.Considering 1-based indexing, the integer i can be used A[i] times to construct the array.Note that sum of
9 min read
Smallest index in the given array that satisfies the given condition
Given an array arr[] of size N and an integer K, the task is to find the smallest index in the array such that: floor(arr[i] / 1) + floor(arr[i + 1] / 2) + floor(arr[i + 2] / 3) + ..... + floor(arr[n - 1] / n - i ) ? K If no such index is found then print -1. Examples: Input: arr[] = {6, 5, 4, 2}, K
6 min read
Count of triplets in an array that satisfy the given conditions
Given an array arr[] of N elements, the task is to find the count of triplets (arr[i], arr[j], arr[k]) such that (arr[i] + arr[j] + arr[k] = L) and (L % arr[i] = L % arr[j] = L % arr[k] = 0.Examples: Input: arr[] = {2, 4, 5, 6, 7} Output: 1 Only possible triplet is {2, 4, 6}Input: arr[] = {4, 4, 4,
13 min read
Find an array of size N that satisfies the given conditions
Given three integers N, S, and K, the task is to create an array of N positive integers such that the bitwise OR of any two consecutive elements from the array is odd and there are exactly K subarrays with a sum equal to S where 1 ? K ? N / 2. Examples: Input: N = 4, K = 2, S = 6 Output: 6 7 6 7 Her
8 min read
Find maximum value of Indices of Array that satisfy the given conditions
Given an integer N (N ? 5) Then assume you have two infinite arrays X and Y where X[] is an array of element N and each element of Y[] is 2i where i is the index of the array, the task is to find two indices let's say A and B which are the maximum value of the index at which the prefix sum in X[] is
9 min read
Check if a cycle of length 3 exists or not in a graph that satisfy a given condition
Given an array Arr of N integers representing the nodes of a graph. The edges are defined between those pairs whose bitwise AND is not equal to zero. The task is to find if there exists a cycle of length 3 or not in the graph.Examples: Input: Arr[] = {26, 33, 35, 40, 50} Output: YesA cycle exists be
2 min read
Queries to check whether a given digit is present in the given Range
Pre-requisites: Segment Tree Given an array of digits arr[]. Given a number of range [L, R] and a digit X with each range. The task is to check for each given range [L, R] whether the digit X is present within that range in the array arr[]. Examples: Input : arr = [1, 3, 3, 9, 8, 7] l1=0, r1=3, x=2
11 min read
Check if every row in given Matrix contains all the integers from 1 to N
Given a matrix arr[][] of size M*N containing only positive integers, the task is to check if every row contains all the integers from 1 to N. Examples: Input: arr[][] = {{1, 4, 2, 3}, {2, 3, 4, 1}, {3, 4, 2, 1}}Output: YesExplanation: Every row contains all the numbers from 1 to 4 Input: arr[][] =
5 min read
Find if a crest is present in the index range [L, R] of the given array
Given an array arr[] of N distinct elements and an index range [L, R]. The task is to find whether a crest is present in that index range in the array or not. Any element arr[i] in the subarray arr[L...R] is called a crest if all the elements of the subarray arr[L...i] are strictly increasing and al
6 min read