Sunday, January 12, 2025
Google search engine
HomeData Modelling & AICount of subarrays of size K with elements having even frequencies

Count of subarrays of size K with elements having even frequencies

Given an array arr[] and an integer K, the task is to count subarrays of size K in which every element appears an even number of times in the subarray.
 

Examples:

Input: arr[] = {1, 4, 2, 10, 2, 10, 0, 20}, K = 4 
Output:
Explanation: Only subarray {2, 10, 2, 10} satisfies the required condition.

Input: arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}, K = 3 
Output:
 

 

Naive Approach: 
The idea is to generate all subarrays of size K and check each of them whether all its elements are present even a number of times or not.

 
Time complexity: O(N*K)
Efficient Approach: 
 

The idea is to use Window Sliding and the XOR concept here.

  1. If the given K is odd, then return 0 as it is guaranteed that at least one number appears an odd number of times if K is odd.
  2. Check if K is greater than the length of arr[] then return 0.
  3. Initialize the following variables:
    • count: Store the count of subarrays of size K with all elements.
    • start: Remove left most element which is no longer part of k size subarray.
    • currXor: Store Xor of the current subarray.
  4. Calculate the Xor of the first K size subarray and check if currXor becomes 0, then increment the count and update currXor by eliminating Xor with arr[start] and increment start by 1.
  5. Traverse arr[] from K to the length of arr[]:
    • Update currXor by doing Xor with arr[i].
    • Increment count if currXor becomes 0 otherwise ignore.
    • Update currXor by eliminating Xor with arr[start].
    • Increment start by 1.
  6. Return count.

Below is the implementation of the above approach:
 

C++




// C++ program to count subarrays
// of size K with all elements
// having even frequencies
#include<bits/stdc++.h>
using namespace std;
 
// Function to return count of
// required subarrays
int countSubarray(int arr[], int K,
                             int N)
{
     
    // If K is odd
    if (K % 2 != 0)
         
        // Not possible to have
        // any such subarrays
        return 0;
 
    if (N < K)
        return 0;
 
    // Stores the starting index
    // of every subarrays
    int start = 0;
 
    int i = 0;
     
    // Stores the count of
    // required subarrays
    int count = 0;
     
    // Stores Xor of the
    // current subarray.
    int currXor = arr[i++];
 
    // Xor of first subarray
    // of size K
    while (i < K)
    {
        currXor ^= arr[i];
        i++;
    }
 
    // If all elements appear
    // even number of times,
    // increase the count of
    // such subarrays
    if (currXor == 0)
        count++;
 
    // Remove the starting element
    // from the current subarray
    currXor ^= arr[start++];
 
    // Traverse the array
    // for the remaining
    // subarrays
    while (i < N)
    {
         
        // Update Xor by adding the
        // last element of the
        // current subarray
        currXor ^= arr[i];
         
        // Increment i
        i++;
 
        // If currXor becomes 0,
        // then increment count
        if (currXor == 0)
            count++;
 
        // Update currXor by removing
        // the starting element of the
        // current subarray
        currXor ^= arr[start++];
    }
 
    // Return count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 4, 2, 2, 4 };
    int K = 4;
    int N = sizeof(arr) / sizeof(arr[0]);
     
    cout << (countSubarray(arr, K, N));
}
 
// This code is contributed by chitranayal


Java




// Java program to count subarrays
// of size K with all elements
// having even frequencies
 
import java.util.*;
 
class GFG {
 
    // Function to return count of
    // required subarrays
    static int countSubarray(int[] arr,
                             int K, int N)
    {
        // If K is odd
        if (K % 2 != 0)
            // Not possible to have
            // any such subarrays
            return 0;
 
        if (N < K)
            return 0;
 
        // Stores the starting index
        // of every subarrays
        int start = 0;
 
        int i = 0;
        // Stores the count of
        // required subarrays
        int count = 0;
        // Stores Xor of the
        // current subarray.
        int currXor = arr[i++];
 
        // Xor of first subarray
        // of size K
        while (i < K) {
            currXor ^= arr[i];
            i++;
        }
 
        // If all elements appear
        // even number of times,
        // increase the count of
        // such subarrays
        if (currXor == 0)
            count++;
 
        // Remove the starting element
        // from the current subarray
        currXor ^= arr[start++];
 
        // Traverse the array
        // for the remaining
        // subarrays
        while (i < N) {
            // Update Xor by adding the
            // last element of the
            // current subarray
            currXor ^= arr[i];
            // Increment i
            i++;
 
            // If currXor becomes 0,
            // then increment count
            if (currXor == 0)
                count++;
 
            // Update currXor by removing
            // the starting element of the
            // current subarray
            currXor ^= arr[start++];
        }
 
        // Return count
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 2, 4, 4, 2, 2, 4 };
        int K = 4;
        int N = arr.length;
        System.out.println(
            countSubarray(arr, K, N));
    }
}


Python3




# Python3 program to count subarrays
# of size K with all elements
# having even frequencies
 
# Function to return count of
# required subarrays
def countSubarray(arr, K, N):
     
    # If K is odd
    if (K % 2 != 0):
         
        # Not possible to have
        # any such subarrays
        return 0
 
    if (N < K):
        return 0
 
    # Stores the starting index
    # of every subarrays
    start = 0
    i = 0
     
    # Stores the count of
    # required subarrays
    count = 0
     
    # Stores Xor of the
    # current subarray.
    currXor = arr[i]
    i += 1
 
    # Xor of first subarray
    # of size K
    while (i < K):
        currXor ^= arr[i]
        i += 1
 
    # If all elements appear
    # even number of times,
    # increase the count of
    # such subarrays
    if (currXor == 0):
        count += 1
 
    # Remove the starting element
    # from the current subarray
    currXor ^= arr[start]
    start += 1
 
    # Traverse the array
    # for the remaining
    # subarrays
    while (i < N):
         
        # Update Xor by adding the
        # last element of the
        # current subarray
        currXor ^= arr[i]
         
        # Increment i
        i += 1
 
        # If currXor becomes 0,
        # then increment count
        if (currXor == 0):
            count += 1
 
        # Update currXor by removing
        # the starting element of the
        # current subarray
        currXor ^= arr[start]
        start += 1
 
    # Return count
    return count
     
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 4, 4, 2, 2, 4 ]
    K = 4
    N = len(arr)
     
    print(countSubarray(arr, K, N))
 
# This code is contributed by mohit kumar 29   


C#




// C# program to count subarrays
// of size K with all elements
// having even frequencies
using System;
class GFG{
 
// Function to return count of
// required subarrays
static int countSubarray(int[] arr,
                         int K, int N)
{
    // If K is odd
    if (K % 2 != 0)
     
        // Not possible to have
        // any such subarrays
        return 0;
 
    if (N < K)
        return 0;
 
    // Stores the starting index
    // of every subarrays
    int start = 0;
 
    int i = 0;
     
    // Stores the count of
    // required subarrays
    int count = 0;
     
    // Stores Xor of the
    // current subarray.
    int currXor = arr[i++];
 
    // Xor of first subarray
    // of size K
    while (i < K)
    {
        currXor ^= arr[i];
        i++;
    }
 
    // If all elements appear
    // even number of times,
    // increase the count of
    // such subarrays
    if (currXor == 0)
        count++;
 
    // Remove the starting element
    // from the current subarray
    currXor ^= arr[start++];
 
    // Traverse the array
    // for the remaining
    // subarrays
    while (i < N)
    {
        // Update Xor by adding the
        // last element of the
        // current subarray
        currXor ^= arr[i];
         
        // Increment i
        i++;
 
        // If currXor becomes 0,
        // then increment count
        if (currXor == 0)
            count++;
 
        // Update currXor by removing
        // the starting element of the
        // current subarray
        currXor ^= arr[start++];
    }
 
    // Return count
    return count;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 2, 4, 4, 2, 2, 4 };
    int K = 4;
    int N = arr.Length;
    Console.Write(countSubarray(arr, K, N));
}
}
 
// This code is contributed by Akanksha_Rai


Javascript




<script>
 
// Javascript program to count subarrays
// of size K with all elements
// having even frequencies
 
// Function to return count of
// required subarrays
function countSubarray(arr, K, N)
{
     
    // If K is odd
    if (K % 2 != 0)
         
        // Not possible to have
        // any such subarrays
        return 0;
 
    if (N < K)
        return 0;
 
    // Stores the starting index
    // of every subarrays
    var start = 0;
 
    var i = 0;
     
    // Stores the count of
    // required subarrays
    var count = 0;
     
    // Stores Xor of the
    // current subarray.
    var currXor = arr[i];
    i++;
 
    // Xor of first subarray
    // of size K
    while (i < K)
    {
        currXor ^= arr[i];
        i++;
    }
 
    // If all elements appear
    // even number of times,
    // increase the count of
    // such subarrays
    if (currXor == 0)
        count++;
 
    // Remove the starting element
    // from the current subarray
    currXor ^= arr[start];
    start++;
 
    // Traverse the array
    // for the remaining
    // subarrays
    while (i < N)
    {
         
        // Update Xor by adding the
        // last element of the
        // current subarray
        currXor ^= arr[i];
         
        // Increment i
        i++;
 
        // If currXor becomes 0,
        // then increment count
        if (currXor == 0)
            count++;
 
        // Update currXor by removing
        // the starting element of the
        // current subarray
        currXor ^= arr[start];
        start++;
    }
 
    // Return count
    return count;
}
 
// Driver Code
    var arr = [2, 4, 4, 2, 2, 4];
    var K = 4;
    var N = arr.length;
     
    document.write(countSubarray(arr, K, N));
 
</script>


Output: 

3

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments