Count of subarrays which contains a given number exactly K times
Last Updated :
02 Jun, 2021
Given an array A[] of N elements consisting of values from 1 to N with duplicates, the task is to find the total number of subarrays that contain a given number num exactly K times.
Examples:
Input: A[] = {1, 2, 1, 5, 1}, num = 1, K = 2
Output: 2
Explanation:
Subarrays {1, 2, 1, 5}, {1, 2, 1}, {2, 1, 5, 1} and {1, 5, 1} contains 1 exactly twice.
Input: A[] = {1, 5, 3, 5, 7, 5, 6, 5, 10, 5, 12, 5}, num = 5, K = 3
Output: 14
Naive Approach: A simple solution is to generate all the subarrays of the given array and count the number of subarrays in which the given number occurs exactly K times.
Time complexity: O(N2) where N is the size of the given array.
Efficient Approach:
- Store the indices which contain the given number num.
- Traverse the indices[] array and calculate the number of subarrays possible for every K indices.
- The number of subarrays possible for any K indices of num is equal to the
Product of (ith index - (i-1)th index) and ( (i + K)th index - (i+(K - 1))th index)
- The count of all such subarrays gives the count of the total possible subarrays in the given array.
Below is the implementation of the above approach:
C++
// C++ program to count subarrays
// which contains a given number
// exactly K times
#include <bits/stdc++.h>
using namespace std;
// Function to return
// the count of subarrays
// which contains given
// number exactly K times
int countSubarrays(int A[], int num,
int K, int size)
{
// Store the indices
// containing num
vector<int> indices;
for (int i = 0; i < size; i++) {
if (A[i] == num)
indices.push_back(i);
}
// If the occurrence of num
// in the entire array
// is less than K
if (indices.size() < K)
// No such subarrays are possible
return 0;
// Store the previous
// index of num
int prev = -1;
// Store the count of
// total subarrays
int ans = 0;
// Store the count of
// subarrays for current
// K occurrences
int ctr = 0;
for (int i = 0;
i <= indices.size() - K;
i++) {
ctr = indices[i] - prev;
if (i < indices.size() - K) {
ctr *= (indices[i + K]
- indices[i + K - 1]);
}
else {
ctr *= ((size - 1)
- indices[i + K - 1] + 1);
}
ans += ctr;
prev = indices[i];
}
return ans;
}
// Driver code
int main()
{
int A[] = { 1, 5, 3, 5, 7, 5, 6,
5, 10, 5, 12, 5 };
int num = 5;
int K = 3;
int size = sizeof(A) / sizeof(int);
cout << countSubarrays(A, num, K, size);
return 0;
}
Java
// Java program to count subarrays
// which contains a given number
// exactly K times
import java.util.*;
public class Main {
// Function to return
// the count of subarrays
// which contains given
// number exactly K times
public static int countSubarrays(
int A[], int num,
int K, int size)
{
// Store the indices
// containing num
ArrayList<Integer> indices
= new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
if (A[i] == num) {
indices.add(i);
}
}
if (indices.size() < K) {
return 0;
}
// Store the previous
// index of num
int prev = -1;
// Store the count of
// total subarrays
int ans = 0;
// Store the count of
// subarrays for current
// K occurrences
int ctr = 0;
for (int i = 0;
i <= indices.size() - K;
i++) {
ctr = indices.get(i) - prev;
if (i < indices.size() - K) {
ctr *= (indices.get(i + K)
- indices.get(i + K - 1));
}
else {
ctr *= ((size - 1)
- indices.get(i + K - 1) + 1);
}
ans += ctr;
prev = indices.get(i);
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int A[] = { 1, 5, 3, 5, 7, 5,
6, 5, 10, 5, 12, 5 };
int num = 5;
int K = 3;
int size = A.length;
System.out.println(
countSubarrays(A, num, K, size));
}
}
Python3
# Python3 program to
# count subarrays which
# contains a given number
# exactly K times
# Function to return
# the count of subarrays
# which contains given
# number exactly K times
def countSubarrays(A, num,
K, size):
# Store the indices
# containing num
indices = []
for i in range (size):
if (A[i] == num):
indices.append(i)
# If the occurrence of num
# in the entire array
# is less than K
if (len(indices) < K):
# No such subarrays are possible
return 0
# Store the previous
# index of num
prev = -1
# Store the count of
# total subarrays
ans = 0
# Store the count of
# subarrays for current
# K occurrences
ctr = 0
for i in range (len(indices) - K + 1):
ctr = indices[i] - prev
if (i < len(indices) - K):
ctr *= (indices[i + K] -
indices[i + K - 1])
else:
ctr *= ((size - 1) -
indices[i + K - 1] + 1)
ans += ctr
prev = indices[i]
return ans
# Driver code
if __name__ == "__main__":
A = [1, 5, 3, 5, 7, 5,
6, 5, 10, 5, 12, 5]
num = 5
K = 3
size = len(A)
print(countSubarrays(A, num, K, size))
# This code is contributed by Chitranayal
C#
// C# program to count subarrays
// which contains a given number
// exactly K times
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
// Function to return the count of subarrays
// which contains given number exactly K times
public static int countSubarrays(int[] A, int num,
int K, int size)
{
// Store the indices
// containing num
ArrayList indices = new ArrayList();
for(int i = 0; i < size; i++)
{
if (A[i] == num)
{
indices.Add(i);
}
}
if (indices.Count < K)
{
return 0;
}
// Store the previous
// index of num
int prev = -1;
// Store the count of
// total subarrays
int ans = 0;
// Store the count of
// subarrays for current
// K occurrences
int ctr = 0;
for(int i = 0;
i <= indices.Count - K;
i++)
{
ctr = (int)indices[i] - prev;
if (i < indices.Count - K)
{
ctr *= ((int)indices[i + K] -
(int)indices[i + K - 1]);
}
else
{
ctr *= ((size - 1) -
(int)indices[i + K - 1] + 1);
}
ans += ctr;
prev = (int)indices[i];
}
return ans;
}
// Driver code
static public void Main()
{
int[] A = { 1, 5, 3, 5, 7, 5,
6, 5, 10, 5, 12, 5 };
int num = 5;
int K = 3;
int size = A.Length;
Console.WriteLine(countSubarrays(A, num, K, size));
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// JavaScript program to count subarrays
// which contains a given number
// exactly K times
// Function to return the count of subarrays
// which contains given number exactly K times
function countSubarrays(A, num, K, size)
{
// Store the indices
// containing num
let indices = [];
for(let i = 0; i < size; i++)
{
if (A[i] == num)
{
indices.push(i);
}
}
if (indices.length < K)
{
return 0;
}
// Store the previous
// index of num
let prev = -1;
// Store the count of
// total subarrays
let ans = 0;
// Store the count of
// subarrays for current
// K occurrences
let ctr = 0;
for(let i = 0;
i <= indices.length - K;
i++)
{
ctr = indices[i] - prev;
if (i < indices.length - K)
{
ctr *= (indices[i + K] -
indices[i + K - 1]);
}
else
{
ctr *= ((size - 1) -
indices[i + K - 1] + 1);
}
ans += ctr;
prev = indices[i];
}
return ans;
}
// Driver Code
let A = [ 1, 5, 3, 5, 7, 5,
6, 5, 10, 5, 12, 5 ];
let num = 5;
let K = 3;
let size = A.length;
document.write(countSubarrays(A, num, K, size));
</script>
Time Complexity: O(N), where N is the size of the array.
Space Complexity: O(N)
Similar Reads
Number of sub-strings that contain the given character exactly k times Given the string str, a character c, and an integer k > 0. The task is to find the number of sub-strings that contain the character c exactly k times.Examples: Input: str = "abada", c = 'a', K = 2 Output: 4 All possible sub-strings are "aba", "abad", "bada" and "ada". Input: str = "55555", c = '5
10 min read
Count the number of valid contiguous Subarrays Given an array, arr[] consisting of N integers and integer K, the task is to count the number of contiguous subarrays where each element is in the subarray at least K times. Examples: Input: N = 3, arr[] = {0, 0, 0}, K = 2Output: 3Explanation: [0], [0], [0] - 0[0, 0], [0, 0] - 2[0, 0, 0] - 1total =
6 min read
Count of Subarrays with sum equals k in given Binary Array Given a binary array arr[] and an integer k, the task is to find the count of non-empty subarrays with a sum equal to k.Examples:Input: arr[] = {1, 0, 1, 1, 0, 1}, k = 2Output: 6Explanation: All valid subarrays are: {1, 0, 1}, {0, 1, 1}, {1, 1}, {1, 0, 1}, {0, 1, 1, 0}, {1, 1, 0}.Input: arr[] = {0,
10 min read
Count of Subarrays which Contain the Length of that Subarray 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 = 3Output: 1Explanation: Only the subarray {1}, with a length 1, contains its own length. Input: A = [1, 2, 3, 4, 5], N = 5Output: 9Explan
8 min read
Count subarrays with equal number of 1's and 0's Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0's and 1's. Examples: Input: arr[] = {1, 0, 0, 1, 0, 1, 1}Output: 8Explanation: The index range for the 8 sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), (4, 5)(2, 5), (0, 5), (1,
14 min read
Count subarrays with equal number of occurrences of two given elements Given an array and two integers say, x and y, find the number of subarrays in which the number of occurrences of x is equal to the number of occurrences of y. Examples: Input : arr[] = {1, 2, 1}, x = 1, y = 2 Output : 2 The possible sub-arrays have same equal number of occurrences of x and y are: 1)
14 min read