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 even number of times in the subarray.

Examples:

Input: arr[] = {1, 4, 2, 10, 2, 10, 0, 20}, K = 4
Output: 1
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:  0

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



Time complexity: O(N*K)

Efficient Approach:

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

  1. If  the given K is odd, then return 0 as it is guaranteed that at least one number appears odd number of time if K is odd.
  2. Check if K is greater than the length of arr[] then return 0.
  3. Initialize 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 current subarray.
  4. Calculate the Xor of first K size subarray and check if currXor becomes 0, then increment count and update currXor by eliminating Xor with arr[start] and increment start by 1.
  5. Traverse arr[] from K to length of arr[]:
    • Update currXor by doing Xor with arr[i].
    • Increment count if currXor become 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
    // evern 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
    # evern 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    

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
    // evern 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

chevron_right


Output:

3

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.