Open In App

Count subarrays consisting of first K natural numbers in descending order

Improve
Improve
Like Article
Like
Save
Share
Report

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


Java




// Java program for the above approach
import java.util.*;
 
public class GFG {
 
    // Function to count subarrays having the decreasing sequence K to 1
    static int countSubarray(int[] arr, int n, int k) {
        // To store the answer
        int ans = 0;
 
        // Find all subarrays
        for (int i = 0; i < n; i++) {
            // To store the 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 consists of the first
                    // K natural numbers in descending order
                    if (count == 0) {
                        ans++;
                    }
                }
            }
        }
        return ans;
    }
 
    // 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));
    }
}


Python3




# Python3 program for the above approach
# Function to count subarrays having the decreasing sequence K to 1
def count_subarray(arr, n, k):
    # To store the answer
    ans = 0
     
    # Find all subarrays
    for i in range(n):
        # To store length
        length = 0
        for j in range(i, n):
            # Increment the length
            length += 1
             
            # When length is equal to k
            if length == k:
                count = k
                 
                m = i
                while m <= j:
                    if arr[m] == count:
                        count -= 1
                    else:
                        break
                    m += 1
                 
                # When subarray consists of the first K natural numbers
                # in descending order
                if count == 0:
                    ans += 1
                     
    return ans
 
# 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(count_subarray(arr, N, K))


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)
    {
        // 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
    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));
    }
}


Javascript




// Javascript program for the above approach
// Function to count subarrays having a decreasing sequence of length K to 1
function CountSubarray(arr, n, k) {
    let ans = 0;  // To store the count of valid subarrays
     
    // Loop through the array to find subarrays
    for (let i = 0; i < n; i++) {
        let length = 0;  // To store the current subarray length
        for (let j = i; j < n; j++) {
            length++;  // Increment the subarray length
             
            // Check if the subarray length is equal to K
            if (length === k) {
                let count = k;  // Counter to track the decreasing sequence from K to 1
                let m = i;  // Index to traverse the subarray
                 
                // Check if the subarray follows the decreasing sequence
                while (m <= j) {
                    if (arr[m] === count) {
                        count--;
                    } else {
                        break
                    }
                    m++;
                }
                 
                // If the counter reaches 0, it means the subarray
                // consists of the required sequence
                if (count === 0) {
                    ans++;  // Increment the count of valid subarrays
                }
            }
        }
    }
     
    return ans;  // Return the total count of valid subarrays
}
 
// Driver Code
const arr = [1, 2, 3, 7, 9, 3, 2, 1, 8, 3, 2, 1];
const N = arr.length;  // Get the length of the array
const K = 3;  // Define the required sequence length
 
// Function Call and Output
console.log(CountSubarray(arr, N, K));


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)



Last Updated : 26 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads