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

19 Jan, 2022
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++
Java
Python3
C#
Javascript
// 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 subarrayint 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 Functionint main(){    int arr[] = { 4, 1, 3, 2, 5, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << countOfSubarrays(arr, n) << endl;    return 0;}
// Java Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarrayclass GFG{ // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarraystatic 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 codepublic 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 Implementation to Count the no. of# Sub-arrays which contains all elements# from 1 to length of subarrayimport 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 subarraydef 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 codeif __name__ == "__main__" :     arr = [ 4, 1, 3, 2, 5, 6 ];    n = len(arr);    print(countOfSubarrays(arr, n)); # This code is contributed by AnkitRai01
// C# Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarrayusing System; class GFG{ // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarraystatic 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 codepublic 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
<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 subarrayfunction 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 Functionvar arr = [4, 1, 3, 2, 5, 6 ];var n = arr.length;document.write( countOfSubarrays(arr, n) ); // This code is contributed by importantly.</script>
5
 
Time Complexity: O(N) 
ankthon
princiraj1992
importantly
khushboogoyal499
sumitgumber28
subarray
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array