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

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 contains 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
Explanantion:
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
Explanantion:
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 subarray.

Effiecient Approach: Create a vector which maps each element of the array with its index in a 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
chevron_right

Output:
5

Time Complexity: O(N)

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01, princiraj1992

Article Tags :
Practice Tags :