Count of Subarrays which Contain the Length of that Subarray
Last Updated :
01 Mar, 2023
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 = 3
Output: 1
Explanation: Only the subarray {1}, with a length 1, contains its own length.
Input: A = [1, 2, 3, 4, 5], N = 5
Output: 9
Explanation: The subarrays {1}, {1, 2}, {2, 3}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5},
{1, 2, 3, 4}, {2, 3, 4, 5}, {1, 2, 3, 4, 5} contain their own length.
Approach: Follow the below idea to solve the problem:
First, form each and every subarray of A. Then, check if the length of the subarray is present in that subarray.
Follow the steps mentioned below to implement the idea:
- Iterate over the array from i = 0 to N:
- Iterate in a nested loop from j = i to N:
- The subarray created is from i to j.
- Traverse the subarray and check if the length is present in the subarray.
- If present, then increment the count.
- The final count is the required answer.
Below is the implementation for the above approach:
C++
// C++ code to implement the approach
#include <iostream>
using namespace std;
// Function to find the count of the subarrays
// that contain their own length
int findCount(int arr[], int N)
{
int counts = 0;
// Forming all possible subarrays
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N + 1; j++) {
// Checking if the length is pre