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:
Count of K length subarrays containing only 1s in given Binary String
Next article icon

Count of Subarrays in an array containing numbers from 1 to the length of subarray

Last Updated : 30 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array.

Examples: 

Input: arr[] = {4, 1, 3, 2, 5, 6} 
Output: 5 
Explanation: 
Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1, 3, 2}, {4, 1, 3, 2, 5}, {4, 1, 3, 2, 5, 6} } 
Count(Sub-arrays) = 5 

Input: arr[] = {3, 2, 4, 1} 
Output: 2 
Explanation: 
Desired Sub-arrays = { {1}, {3, 2, 4, 1} } 
Count(Sub-arrays) = 2 
 

Naive Approach: Generate all subarrays of the array and check for each subarray that it contains each element 1 to the length of the subarray.

Efficient Approach: Create a vector that maps each element of the array with its index in sorted order. Now iterate over this vector and check whether the difference of maximum and minimum index till the ith element is less than the number of elements iterated till now, which is the value of i itself.

Below is the implementation of the above approach 

C++




// C++ Implementation to Count the no. of
// Sub-arrays which contains all elements
// from 1 to length of subarray
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number
// Sub-arrays which contains all elements
// 1 to length of subarray
int countOfSubarrays(int* arr, int n)
{
    int count = 0;
    vector<int> v(n + 1);
 
    // Map all elements of array with their index
    for (int i = 0; i < n; i++)
        v[arr[i]] = i;
 
    // Set the max and min index equal to the
    // min and max value of integer respectively.
    int maximum = INT_MIN;
    int minimum = INT_MAX;
 
    for (int i = 1; i <= n; i++) {
 
        // Update the value of maximum index
        maximum = max(maximum, v[i]);
 
        // Update the value of minimum index
        minimum = min(minimum, v[i]);
 
        // Increase the counter if difference of
        // max. and min. index is less than the
        // elements iterated till now
        if (maximum - minimum < i)
            count = count + 1;
    }
 
    return count;
}
 
// Driver Function
int main()
{
    int arr[] = { 4, 1, 3, 2, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countOfSubarrays(arr, n) << endl;
    return 0;
}
 
 

Java




// Java Implementation to Count the no. of
// Sub-arrays which contains all elements
// from 1 to length of subarray
class GFG
{
 
// Function to count the number
// Sub-arrays which contains all elements
// 1 to length of subarray
static int countOfSubarrays(int []arr, int n)
{
    int count = 0;
    int []v = new int[n + 1];
 
    // Map all elements of array with their index
    for (int i = 0; i < n; i++)
        v[arr[i]] = i;
 
    // Set the max and min index equal to the
    // min and max value of integer respectively.
    int maximum = Integer.MIN_VALUE;
    int minimum = Integer.MAX_VALUE;
 
    for (int i = 1; i <= n; i++)
    {
 
        // Update the value of maximum index
        maximum = Math.max(maximum, v[i]);
 
        // Update the value of minimum index
        minimum = Math.min(minimum, v[i]);
 
        // Increase the counter if difference of
        // max. and min. index is less than the
        // elements iterated till now
        if (maximum - minimum < i)
            count = count + 1;
    }
 
    return count;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 4, 1, 3, 2, 5, 6 };
    int n = arr.length;
    System.out.print(countOfSubarrays(arr, n) +"\n");
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Python3




# Python3 Implementation to Count the no. of
# Sub-arrays which contains all elements
# from 1 to length of subarray
import sys
 
INT_MAX = sys.maxsize;
INT_MIN = -(sys.maxsize - 1);
 
# Function to count the number
# Sub-arrays which contains all elements
# 1 to length of subarray
def countOfSubarrays(arr, n) :
 
    count = 0;
    v = [0]*(n + 1);
 
    # Map all elements of array with their index
    for i in range(n) :
        v[arr[i]] = i;
 
    # Set the max and min index equal to the
    # min and max value of integer respectively.
    maximum = INT_MIN;
    minimum = INT_MAX;
 
    for i in range(1, n + 1) :
 
        # Update the value of maximum index
        maximum = max(maximum, v[i]);
 
        # Update the value of minimum index
        minimum = min(minimum, v[i]);
 
        # Increase the counter if difference of
        # max. and min. index is less than the
        # elements iterated till now
        if (maximum - minimum < i) :
            count = count + 1;
 
    return count;
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 4, 1, 3, 2, 5, 6 ];
    n = len(arr);
    print(countOfSubarrays(arr, n));
 
# This code is contributed by AnkitRai01
 
 

C#




// C# Implementation to Count the no. of
// Sub-arrays which contains all elements
// from 1 to length of subarray
using System;
 
class GFG
{
 
// Function to count the number
// Sub-arrays which contains all elements
// 1 to length of subarray
static int countOfSubarrays(int []arr, int n)
{
    int count = 0;
    int []v = new int[n + 1];
 
    // Map all elements of array with their index
    for (int i = 0; i < n; i++)
        v[arr[i]] = i;
 
    // Set the max and min index equal to the
    // min and max value of integer respectively.
    int maximum = int.MinValue;
    int minimum = int.MaxValue;
 
    for (int i = 1; i <= n; i++)
    {
 
        // Update the value of maximum index
        maximum = Math.Max(maximum, v[i]);
 
        // Update the value of minimum index
        minimum = Math.Min(minimum, v[i]);
 
        // Increase the counter if difference of
        // max. and min. index is less than the
        // elements iterated till now
        if (maximum - minimum < i)
            count = count + 1;
    }
 
    return count;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 4, 1, 3, 2, 5, 6 };
    int n = arr.Length;
    Console.Write(countOfSubarrays(arr, n) +"\n");
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
// Javascript Implementation to Count the no. of
// Sub-arrays which contains all elements
// from 1 to length of subarray
 
// Function to count the number
// Sub-arrays which contains all elements
// 1 to length of subarray
function countOfSubarrays(arr, n)
{
    var count = 0;
    var v = Array(n + 1);
 
    // Map all elements of array with their index
    for (var i = 0; i < n; i++)
        v[arr[i]] = i;
 
    // Set the max and min index equal to the
    // min and max value of integer respectively.
    var maximum = -1000000000;
    var minimum = 10000000000;
 
    for (var i = 1; i <= n; i++) {
 
        // Update the value of maximum index
        maximum = Math.max(maximum, v[i]);
 
        // Update the value of minimum index
        minimum = Math.min(minimum, v[i]);
 
        // Increase the counter if difference of
        // max. and min. index is less than the
        // elements iterated till now
        if (maximum - minimum < i)
            count = count + 1;
    }
 
    return count;
}
 
// Driver Function
var arr = [4, 1, 3, 2, 5, 6 ];
var n = arr.length;
document.write( countOfSubarrays(arr, n) );
 
// This code is contributed by importantly.
</script>
 
 
Output: 
5

 

Time Complexity: O(N), for traversal over the array.
 Auxiliary Space: O(N), for creating an extra array of size N + 1.



Next Article
Count of K length subarrays containing only 1s in given Binary String

A

AmanGupta65
Improve
Article Tags :
  • Arrays
  • DSA
  • subarray
Practice Tags :
  • Arrays

Similar Reads

  • Count of Subarrays which Contain the Length of that Subarray
    Given an array A[] of length N, the task is to count the number of subarrays of A[] that contain the length of that subarray. Examples: Input: A = {10, 11, 1}, N = 3Output: 1Explanation: Only the subarray {1}, with a length 1, contains its own length. Input: A = [1, 2, 3, 4, 5], N = 5Output: 9Explan
    8 min read
  • Count of subarray that does not contain any subarray with sum 0
    Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not co
    11 min read
  • Count of K length subarrays containing only 1s in given Binary String
    Given a binary string str, the task is to find the count of K length subarrays containing only 1s. Examples: Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays with 1 ones Input: str = "11111001", K=3Output: 3 Approach: The task can be solved by keeping track of the
    4 min read
  • Count of Subarrays not containing all elements of another Array
    Given two arrays nums[] of size N and target[]. The task is to find the number of non-empty subarrays of nums[] that do not contain every number in the target[]. As the answer can be very large, calculate the result modulo 109+7. Examples: Input: nums = {1, 2, 2}, target = {1, 2}Output: 4Explanation
    12 min read
  • Count of K length subarrays containing only 1s in given Binary String | Set 2
    Given binary string str, the task is to find the count of K length subarrays containing only 1s. Examples Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays of length 1 containing only 1s. Input: str = "11111001", K=3Output: 3 Approach: The given problem can also be
    4 min read
  • Count number of coordinates from an array satisfying the given conditions
    Given an array arr[] consisting of N coordinates in the Cartesian Plane, the task is to find the number of coordinates, such as (X, Y), that satisfies all the following conditions: All possible arr[i][0] must be less than X and arr[i][1] must be equal to Y.All possible arr[i][0] must be greater than
    10 min read
  • Find number of subarrays ending with arr[i] where arr[i] is the minimum element of that subarray
    Given an array, arr[] of size N, the task is to find the number of sub-arrays ending with arr[i] and arr[i] is the minimum element of that sub-array.  Note: Elements in array will be unique. Examples:   Input: arr[] = {3, 1, 2, 4} Output: 1 2 1 1 Explanation: Subarrays ending with 3 where 3 is the m
    6 min read
  • Count subarrays having sum modulo K same as the length of the subarray
    Given an integer K and an array arr[] consisting of N positive integers, the task is to find the number of subarrays whose sum modulo K is equal to the size of the subarray. Examples: Input: arr[] = {1, 4, 3, 2}, K = 3Output: 4Explanation: 1 % 3 = 1 (1 + 4) % 3 = 2 4 % 3 = 1 (3 + 2) % 3 = 2 Therefor
    15 min read
  • Count Subarrays with product of sum and subarray length less than K
    Given an array of positive elements arr[] of length N, the task is to count all the subarrays such that the product of the subarray sum and length of the subarray should be strictly less than K. Examples: Input: arr[] = {6, 2, 1, 4, 3}, K = 10Output: 6Explanation: There are six valid subarrays: {6},
    13 min read
  • Find sum of count of duplicate numbers in all subarrays of given array
    Given an array arr[] of size N. The task it to find the sum of count of duplicate numbers in all subarrays of given array arr[]. For example array {1, 2, 3, 2, 3, 2} has two duplicate elements (i.e, 2 and 3 come more than one time in the array). Examples:Input: N = 2, arr = {3,3}Output: 1Explanation
    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