Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Count subarrays consisting of first K natural numbers in descending order

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given an array arr[] of size N and an integer K, the task is to count the number of subarrays which consists of first K natural numbers in descending order.

Examples:

Input: arr[] = {1, 2, 3, 7, 9, 3, 2, 1, 8, 3, 2, 1}, K = 3
Output: 2
Explanation: The subarray {3, 2, 1} occurs twice in the array.

Input: arr = {100, 7, 6, 5, 4, 3, 2, 1, 100}, K = 6
Output: 1

 

Naive Approach

The idea is to find all subarrays and then find those subarrays whose length is equal to k. After that from those subarrays find the number of subarrays that consist of the first K natural number in decreasing order.

Steps to implement-

  • Initialize a variable ans with value 0 to store the final answer
  • Run two for loops to find all subarray
  • Simultaneously find the length of the subarray
  • If any subarray has a length of K
    • Then check whether it contains the first K natural numbers in descending order
    • If Yes then increment the ans by 1

Code-

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count subarray having
// the decreasing sequence K to 1
int CountSubarray(int arr[], int n,
                  int k)
{
   //To store answer
   int ans=0;
     
   //Find all subarray
   for(int i=0;i<n;i++){
       //To store length
       int length=0;
       for(int j=i;j<n;j++){
           //Increment the length
           length++;
            
           //when length is equal to k
           if(length==k){
             int count=k;
              
             int m=i;
             while(m<=j){
                 if(arr[m]==count){count--;}
                 else{break;}
                 m++;
             }
             
            //when subarray consist of first
            //K natural numbers in descending order
             if(count==0){ans++;}
              
           }
            
       }
   }
   return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 7, 9, 3,
                  2, 1, 8, 3, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function Call
    cout << CountSubarray(arr, N, K);
 
    return 0;
}

Output

2

Time Complexity: O(N3), because of two loops to find all subarray and a third loop to choose subarray which consists of first K natural numbers in descending order
Auxiliary Space: O(1), because no extra space has been used

Approach: The idea is to traverse the array and check if the required decreasing sequence is present starting from the current index or not. Follow the steps below to solve the problem:

  • Initialize two variables, temp to K, that checks the pattern, and count with 0, to store the count of total subarray matched.
  • Traverse the array arr[] using the variable i and do the following:
    • If arr[i] is equal to temp and the value of temp is 1, then increment the count by 1 and update temp as K. Else decrement temp by 1.
    • Otherwise, update temp as temp = K and if arr[i] is equal to K, decrement i by 1.
  • After the above steps, print the value of count as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count subarray having
// the decreasing sequence K to 1
int CountSubarray(int arr[], int n,
                  int k)
{
    int temp = k, count = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Check if required sequence
        // is present or not
        if (arr[i] == temp) {
            if (temp == 1) {
                count++;
                temp = k;
            }
            else
                temp--;
        }
 
        // Reset temp to k
        else {
            temp = k;
            if (arr[i] == k)
                i--;
        }
    }
 
    // Return the count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 7, 9, 3,
                  2, 1, 8, 3, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function Call
    cout << CountSubarray(arr, N, K);
 
    return 0;
}
 
// This code is contributed by Dharanendra L V

Java




// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to count subarray having
  // the decreasing sequence K to 1
  static int CountSubarray(int arr[], int n,
                           int k)
  {
    int temp = k, count = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
      // Check if required sequence
      // is present or not
      if (arr[i] == temp) {
        if (temp == 1) {
          count++;
          temp = k;
        }
        else
          temp--;
      }
 
      // Reset temp to k
      else {
        temp = k;
        if (arr[i] == k)
          i--;
      }
    }
 
    // Return the count
    return count;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 1, 2, 3, 7, 9, 3,
                 2, 1, 8, 3, 2, 1 };
    int N = arr.length;
    int K = 3;
 
    // Function Call
    System.out.println(CountSubarray(arr, N, K));
  }
}
 
// This code is contributed by shivanisinghss2110

Python3




# Python3 program for the above approach
 
# Function to count subarray having
# the decreasing sequence K to 1
def CountSubarray(arr, n, k):
     
    temp = k
    count = 0
 
    # Traverse the array
    for i in range(n):
 
        # Check if required sequence
        # is present or not
        if (arr[i] == temp):
            if (temp == 1):
                count += 1
                temp = k
            else:
                   temp -= 1
 
        # Reset temp to k
        else:
            temp = k
             
            if (arr[i] == k):
                i -= 1
 
    # Return the count
    return count
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 3, 7, 9, 3,
            2, 1, 8, 3, 2, 1 ]
    N = len(arr)
    K = 3
 
    # Function Call
    print(CountSubarray(arr, N, K))
 
# This code is contributed by chitranayal

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to count subarray having
// the decreasing sequence K to 1
static int CountSubarray(int[] arr,
                         int n, int k)
{
    int temp = k, count = 0;
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // Check if required sequence
        // is present or not
        if (arr[i] == temp)
        {
            if (temp == 1)
            {
                count++;
                temp = k;
            }
            else
                temp--;
        }
 
        // Reset temp to k
        else
        {
            temp = k;
             
            if (arr[i] == k)
                i--;
        }
    }
 
    // Return the count
    return count;
}
 
// Driver code
static public void Main()
{
    int[] arr = { 1, 2, 3, 7, 9, 3,
                  2, 1, 8, 3, 2, 1 };
    int N = arr.Length;
    int K = 3;
 
    // Function Call
    Console.Write(CountSubarray(arr, N, K));
}
}
 
// This code is contributed by Dharanendra L V

Javascript




<script>
 
      // JavaScript program for the above approach
 
      // Function to count subarray having
      // the decreasing sequence K to 1
      function CountSubarray(arr, n, k) {
        var temp = k,
          count = 0;
 
        // Traverse the array
        for (var i = 0; i < n; i++)
        {
          // Check if required sequence
          // is present or not
          if (arr[i] == temp)
          {
            if (temp == 1) {
              count++;
              temp = k;
            } else temp--;
          }
 
          // Reset temp to k
          else {
            temp = k;
            if (arr[i] == k) i--;
          }
        }
 
        // Return the count
        return count;
      }
 
      // Driver Code
 
      var arr = [1, 2, 3, 7, 9, 3, 2, 1, 8, 3, 2, 1];
      var N = arr.length;
      var K = 3;
 
      // Function Call
      document.write(CountSubarray(arr, N, K));
       
</script>

Output: 

2

 

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


My Personal Notes arrow_drop_up
Last Updated : 04 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials