Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find an array of size N that satisfies the given conditions
Next article icon

Check if there exist 4 indices in the array satisfying the given condition

Last Updated : 05 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
 
 
Output
YES

Time Complexity: O(N * log(N))
Auxiliary Space: O(N)



Next Article
Find an array of size N that satisfies the given conditions
author
kamabokogonpachiro
Improve
Article Tags :
  • Arrays
  • DSA
  • Searching
  • Binary Search
  • cpp-set
  • prefix-sum
Practice Tags :
  • Arrays
  • Binary Search
  • prefix-sum
  • Searching

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[][] =
    6 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences