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:
Check if all subarrays contains at least one unique element
Next article icon

Check if a non-contiguous subsequence same as the given subarray exists or not

Last Updated : 04 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers and two integer values L and R, indicating the starting and ending indices of a subarray, the task is to check if there exists a non-contiguous subsequence which is same as the given subarray or not. If found to be true, print “Yes”. Otherwise, print “No”.

A non-contiguous subsequence contains at least two consecutive characters from non-consecutive indices.

Examples:

Input: arr[] = {1, 7, 12, 1, 7, 5, 10, 11, 42}, L = 3, R = 6
Output: Yes
Explanation: The non-contiguous subsequence {arr[0], arr[1], arr[5], arr[6]} is same as the subarray {arr[3], .., arr[6]}.

Input: arr[] = {0, 1, 2, -2, 5, 10}, L = 1, R = 3

Naive Approach: The simplest approach is to generate all possible subsequences of the given array and check if any subsequence generated is equal to the given subarray or not. If found to be true, then print “Yes”. Otherwise, print “No”. 

Time Complexity: O(N*2N)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is based on the key observation that there will always be a non-contiguous subsequence if there is at least one occurrence of the first element of the given subarray in the range [0, L – 1] and at least one occurrence of the last element of a subarray in the range [R + 1, N].

Proof of Logic:

If the 1st element of the subarray {arr[L], … arr[R]} also occurs at any index K (K < L), then one such non-contiguous subsequence can be {arr[K], arr[L + 1], …., arr[R]}. 
If the last element of the subarray {arr[L], … arr[R]} also occurs at any index K (K > R), then one such non-contiguous subsequence can be strong>{arr[L], arr[L + 1], …., arr[R – 1], arr[K]}. 
If none of the above two conditions are satisfied, then no such non-contiguous subsequence exists.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Utility Function to check whether
// a subsequence same as the given
// subarray exists or not
bool checkSubsequenceUtil(
    int arr[], int L, int R, int N)
{
    // Check if first element of the
    // subarray is also present before
    for (int i = 0; i < L; i++)
        if (arr[i] == arr[L])
            return true;
 
    // Check if last element of the
    // subarray is also present later
    for (int i = R + 1; i < N; i++)
        if (arr[i] == arr[R])
            return true;
 
    // If above two conditions are
    // not satisfied, then no such
    // subsequence exists
    return false;
}
 
// Function to check and print if a
// subsequence which is same as the
// given subarray is present or not
void checkSubsequence(int arr[], int L,
                      int R, int N)
{
    if (checkSubsequenceUtil(arr, L,
                             R, N)) {
        cout << "YES\n";
    }
    else {
        cout << "NO\n";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 7, 12, 1, 7,
                  5, 10, 11, 42 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int L = 3, R = 6;
 
    // Function Call
    checkSubsequence(arr, L, R, N);
}
 
 

Java




// Java program for the above approach
class GFG{
      
// Utility Function to check whether
// a subsequence same as the given
// subarray exists or not
static boolean checkSubsequenceUtil(int arr[], int L,
                                    int R, int N)
{
     
    // Check if first element of the
    // subarray is also present before
    for(int i = 0; i < L; i++)
        if (arr[i] == arr[L])
            return true;
  
    // Check if last element of the
    // subarray is also present later
    for(int i = R + 1; i < N; i++)
        if (arr[i] == arr[R])
            return true;
             
    // If above two conditions are
    // not satisfied, then no such
    // subsequence exists
    return false;
}
  
// Function to check and print if a
// subsequence which is same as the
// given subarray is present or not
static void checkSubsequence(int arr[], int L,
                             int R, int N)
{
    if (checkSubsequenceUtil(arr, L,
                             R, N))
    {
        System.out.print("YES\n");
    }
    else
    {
        System.out.print("NO\n");
    }
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 7, 12, 1, 7,
                  5, 10, 11, 42 };
    int N = arr.length;
    int L = 3, R = 6;
  
    // Function Call
    checkSubsequence(arr, L, R, N);
}
}
  
// This code is contributed by sanjoy_62
 
 

Python3




# Python3 program for the above approach
  
# Utility Function to check whether
# a subsequence same as the given
# subarray exists or not
def checkSubsequenceUtil(arr, L, R, N):
         
    # Check if first element of the
    # subarray is also present before
    for i in range(L):
        if (arr[i] == arr[L]):
            return True
  
    # Check if last element of the
    # subarray is also present later
    for i in range(R + 1, N, 1):
        if (arr[i] == arr[R]):
            return True
  
    # If above two conditions are
    # not satisfied, then no such
    # subsequence exists
    return False
 
# Function to check and print if a
# subsequence which is same as the
# given subarray is present or not
def checkSubsequence(arr, L, R, N):
     
    if (checkSubsequenceUtil(arr, L,R, N)):
        print("YES")
    else:
        print("NO")
         
# Driver Code
arr = [ 1, 7, 12, 1, 7,
        5, 10, 11, 42 ]
N = len(arr)
L = 3
R = 6
  
# Function Call
checkSubsequence(arr, L, R, N)
 
# This code is contributed by susmitakundugoaldanga
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
       
// Utility Function to check whether
// a subsequence same as the given
// subarray exists or not
static bool checkSubsequenceUtil(int[] arr, int L,
                                 int R, int N)
{
     
    // Check if first element of the
    // subarray is also present before
    for(int i = 0; i < L; i++)
        if (arr[i] == arr[L])
            return true;
   
    // Check if last element of the
    // subarray is also present later
    for(int i = R + 1; i < N; i++)
        if (arr[i] == arr[R])
            return true;
              
    // If above two conditions are
    // not satisfied, then no such
    // subsequence exists
    return false;
}
   
// Function to check and print if a
// subsequence which is same as the
// given subarray is present or not
static void checkSubsequence(int[] arr, int L,
                             int R, int N)
{
    if (checkSubsequenceUtil(arr, L,
                             R, N))
    {
        Console.Write("YES\n");
    }
    else
    {
        Console.Write("NO\n");
    }
}
   
// Driver code
public static void Main()
{
    int[] arr = { 1, 7, 12, 1, 7,
                  5, 10, 11, 42 };
                   
    int N = arr.Length;
    int L = 3, R = 6;
   
    // Function Call
    checkSubsequence(arr, L, R, N);
}
}
 
// This code is contributed by code_hunt
 
 

Javascript




<script>
// javascript program to implement
// the above approach
 
// Utility Function to check whether
// a subsequence same as the given
// subarray exists or not
function checkSubsequenceUtil(arr, L,
                                    R, N)
{
      
    // Check if first element of the
    // subarray is also present before
    for(let i = 0; i < L; i++)
        if (arr[i] == arr[L])
            return true;
   
    // Check if last element of the
    // subarray is also present later
    for(let i = R + 1; i < N; i++)
        if (arr[i] == arr[R])
            return true;
              
    // If above two conditions are
    // not satisfied, then no such
    // subsequence exists
    return false;
}
   
// Function to check and print if a
// subsequence which is same as the
// given subarray is present or not
function checkSubsequence(arr, L,
                             R, N)
{
    if (checkSubsequenceUtil(arr, L,
                             R, N))
    {
        document.write("YES\n");
    }
    else
    {
        document.write("NO\n");
    }
}
 
// Driver code
 
    let arr = [ 1, 7, 12, 1, 7,
                  5, 10, 11, 42 ];
    let N = arr.length;
    let L = 3, R = 6;
   
    // Function Call
    checkSubsequence(arr, L, R, N);
     
    // This code is contributed by souravghosh0416.
</script>
 
 
Output: 
YES

 

Time Complexity: O(N)
Auxiliary Space: O(1)



Next Article
Check if all subarrays contains at least one unique element

S

shekabhi1208
Improve
Article Tags :
  • Arrays
  • DSA
  • Searching
  • Technical Scripter
  • subarray
  • subsequence
  • Technical Scripter 2020
Practice Tags :
  • Arrays
  • Searching

Similar Reads

  • Length of the longest increasing subsequence which does not contain a given sequence as Subarray
    Given two arrays arr[] and arr1[] of lengths N and M respectively, the task is to find the longest increasing subsequence of array arr[] such that it does not contain array arr1[] as subarray. Examples: Input: arr[] = {5, 3, 9, 3, 4, 7}, arr1[] = {3, 3, 7}Output: 4Explanation: Required longest incre
    14 min read
  • 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 subarray with given product exists in an array
    Given an array of both positive and negative integers and a number K., The task is to check if any subarray with product K is present in the array or not. Examples: Input: arr[] = {-2, -1, 3, -4, 5}, K = 2Output: YESInput: arr[] = {3, -1, -1, -1, 5}, K = 3Output: YESApproach: The code provided seeks
    7 min read
  • Check if a Subarray exists with sums as a multiple of k
    Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer. Note: The length of the array won't exceed 10,000. You may assume th
    8 min read
  • Check if all subarrays contains at least one unique element
    Given an array arr[] consisting of N integers, the task is to check if all subarrays of the array have at least one unique element in it or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 1}Output: YesExplanation:For Subarrays of size 1: {1}, {2}, {
    11 min read
  • Check if two same sub-sequences exist in a string or not
    Given a string, the task is to check if there exist two equal sub-sequences in the given string. Two sub-sequences are said to be equal if they have the same characters arranged in the same lexicographical order but the position of characters differs from that in the original string. Examples: Input
    5 min read
  • Check if there exist 4 indices in the array satisfying the given condition
    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 < NSum of the subarray from A[p] to A[q - 1] is XSum of the subarray from A[q] to A[
    8 min read
  • Check if a subarray exists with sum greater than the given Array
    Given an array of integers arr, the task is to check if there is a subarray (except the given array) such that the sum of its elements is greater than or equal to the sum of elements of the given array. If no such subarray is possible, print No, else print Yes.Examples: Input: arr = {5, 6, 7, 8} Out
    7 min read
  • Count of possible subarrays and subsequences using given length of Array
    Given an integer N which denotes the length of an array, the task is to count the number of subarray and subsequence possible with the given length of the array.Examples: Input: N = 5 Output: Count of subarray = 15 Count of subsequence = 32Input: N = 3 Output: Count of subarray = 6 Count of subseque
    3 min read
  • Subsequences of given string consisting of non-repeating characters
    Given a string str of length N, the task is to print all possible distinct subsequences of the string str which consists of non-repeating characters only. Examples: Input: str = "abac" Output: a ab abc ac b ba bac bc c Explanation: All possible distinct subsequences of the strings are { a, aa, aac,
    7 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