Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count of subarrays of size K with elements having even frequencies
Next article icon

Count non-overlapping Subarrays of size K with equal alternate elements

Last Updated : 28 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of length N, the task is to find the count of non-overlapping subarrays of size K such that the alternate elements are equal.

Examples:

Input: arr[] = {2, 4, 2, 7}, K = 3
Output: 1
Explanation:  Given subarray {2, 4, 2} is a valid array because the elements in even position(index no.0 and 2) are equal. Hence the count of the subarrays with size K = 3 is 1.

Input: arr[] =  {5, 2, 5, 2, 3, 9, 7, 9, 7}, K = 4
Output: 2
Explanation:  Subarray {5, 2, 5, 2} and {9, 7, 9, 7} are valid subarrays because the elements in even position(index no.0 and 2) and odd positions(index no.1 and 3) are equal.  Hence the count of the subarrays with size K = 4 is 2.

Approach: Implement the idea below to solve the problem

Initially find all the non-overlapping subarrays where  alternate elements are equal. Comparing the lengths of each such subarray with K, we can find out how many valid subarrays of size K can be extracted from each of those.

Follow the below steps to implement the idea:

  • Initialize t = 2  in starting and c = 0, to maintain the count of subarrays.
  • Iterate over the array from index 2.
  • Whenever we found arr[i] = arr[i-2], increment t by 1.
  • When t gets equal to K, increase c by 1 and reset t = 0.
  • If the length of the given array arr[] is less than 2, see the value of K and return the output accordingly.
  • After iterating over the array, return c as the count subarrays.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
#include <iostream>
using namespace std;
 
// Function to find the count of subarrays
int fun(int arr[], int k, int n)
{
 
  // For checking the length of array
  if (n <= 2) {
    if (k == 1) {
      return n;
    }
    else if (k == 2) {
      return 1;
    }
    else {
      return 0;
    }
  }
  int t = 2;
  int c = 0;
 
  // Loop through the array from 2 to arr.length
  for (int i = 2; i < n; i++)
  {
    // For checking the array elements at odd and
    // even index
    if (arr[i] == arr[i - 2]) {
      t = t + 1;
    }
    else {
      t = 2;
    }
 
    // check whether current size equals k
    if (t == k)
    {
      // Increment the count by 1
      c = c + 1;
      t = 0;
    }
  }
  return c;
}
 
int main() {
 
  int arr[] = { 5, 2, 5, 2, 5, 2, 5, 2, 3, 9, 7, 9, 7 };
  int K = 4;
  int n = sizeof(arr) / sizeof(arr[0]);
 
  // Function call
  cout << fun(arr, K, n) << endl;
 
  return 0;
}
 
// This code is contributed by lokesh.
 
 

Java




// Java code to implement the approach
import java.io.*;
 
class GFG {
 
  // Function to find the cound of subarrays
  static int fun(int[] arr, int k)
  {
 
    // For checking the length of array
    if (arr.length <= 2) {
      if (k == 1) {
        return arr.length;
      }
      else if (k == 2) {
        return 1;
      }
      else {
        return 0;
      }
    }
    int t = 2;
    int c = 0;
 
    // Loop through the array from 2 to arr.length
    for (int i = 2; i < arr.length; i++)
    {
 
      // For checking the array elements at odd and
      // even index
      if (arr[i] == arr[i - 2]) {
        t = t + 1;
      }
      else {
        t = 2;
      }
 
      // check whether current size equals k
      if (t == k)
      {
 
        // Increment the count by 1
        c = c + 1;
        t = 0;
      }
    }
    return c;
  }
 
  public static void main(String[] args)
  {
    int[] arr
      = { 5, 2, 5, 2, 5, 2, 5, 2, 3, 9, 7, 9, 7 };
    int K = 4;
 
    // Function call
    System.out.print(fun(arr, K));
  }
}
 
// This code is contributed by lokeshmvs21.
 
 

Python3




# Python code to implement the approach
 
 
# Function to find the count of subarrays
def fun(arr, k):
 
    # For checking the length of array
    if len(arr) <= 2:
        if k == 1:
            return len(arr)
        elif k == 2:
            return 1
        else:
            return 0
 
    else:
        # For storing current subarray
        t = 2
        c = 0
 
        # Loop through the array from 2 to len(arr)
        for i in range(2, len(arr)):
 
            # For checking the array elements at
            # odd and even index
            if arr[i] == arr[i-2]:
 
                t = t + 1
            else:
                t = 2
 
            # check whether current size
            # equals k
            if t == k:
 
                # Increment the count by 1
                c += 1
                t = 0
        return c
 
 
# Driver code
if __name__ == '__main__':
 
    arr = [5, 2, 5, 2, 5, 2, 5, 2, 3, 9, 7, 9, 7]
    K = 4
 
    # Function call
    print(fun(arr, K))
 
 

C#




// C# code to implement the approach
using System;
 
class GFG {
 
// Function to find the cound of subarrays
static int fun(int[] arr, int k)
{
 
    // For checking the length of array
    if (arr.Length <= 2) {
    if (k == 1) {
        return arr.Length;
    }
    else if (k == 2) {
        return 1;
    }
    else {
        return 0;
    }
    }
    int t = 2;
    int c = 0;
 
    // Loop through the array from 2 to arr.length
    for (int i = 2; i < arr.Length; i++)
    {
 
    // For checking the array elements at odd and
    // even index
    if (arr[i] == arr[i - 2]) {
        t = t + 1;
    }
    else {
        t = 2;
    }
 
    // check whether current size equals k
    if (t == k)
    {
 
        // Increment the count by 1
        c = c + 1;
        t = 0;
    }
    }
    return c;
}
 
static public void Main ()
{
    int[] arr= { 5, 2, 5, 2, 5, 2, 5, 2, 3, 9, 7, 9, 7 };
    int K = 4;
 
    // Function call
    Console.Write(fun(arr, K));
}
}
 
// This code is contributed by Pushpesh Raj.
 
 

Javascript




// javascript code to implement the approach
 
// Function to find the count of subarrays
function fun(arr, k, n)
{
 
  // For checking the length of array
  if (n <= 2) {
    if (k == 1) {
      return n;
    }
    else if (k == 2) {
      return 1;
    }
    else {
      return 0;
    }
  }
  let t = 2;
  let c = 0;
 
  // Loop through the array from 2 to arr.length
  for (let i = 2; i < n; i++)
  {
    // For checking the array elements at odd and
    // even index
    if (arr[i] == arr[i - 2]) {
      t = t + 1;
    }
    else {
      t = 2;
    }
 
    // check whether current size equals k
    if (t == k)
    {
      // Increment the count by 1
      c = c + 1;
      t = 0;
    }
  }
  return c;
}
 
let arr = [ 5, 2, 5, 2, 5, 2, 5, 2, 3, 9, 7, 9, 7 ];
  let K = 4;
  let n = arr.length;
 
  // Function call
  console.log(fun(arr, K, n));
   
  // This code is contributed by garg28harsh.
 
 
Output
3

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

Related Articles:

  • Introduction to Arrays – Data Structures and Algorithms Tutorials


Next Article
Count of subarrays of size K with elements having even frequencies

A

ameygangan19
Improve
Article Tags :
  • Arrays
  • DSA
  • Technical Scripter
  • subarray
  • Technical Scripter 2022
Practice Tags :
  • Arrays

Similar Reads

  • Count of subarrays of size K with average at least M
    Given an array arr[] consisting of N integers and two positive integers K and M, the task is to find the number of subarrays of size K whose average is at least M. Examples: Input: arr[] = {2, 3, 3, 4, 4, 4, 5, 6, 6}, K = 3, M = 4Output: 4Explanation:Below are the subarrays of size K(= 3) whose aver
    7 min read
  • Count subarrays with same even and odd elements
    Given an array of N integers, count number of even-odd subarrays. An even - odd subarray is a subarray that contains the same number of even as well as odd integers. Examples : Input : arr[] = {2, 5, 7, 8} Output : 3 Explanation : There are total 3 even-odd subarrays. 1) {2, 5} 2) {7, 8} 3) {2, 5, 7
    15+ min read
  • Maximize count of non-overlapping subarrays with sum K
    Given an array arr[] and an integer K, the task is to print the maximum number of non-overlapping subarrays with a sum equal to K. Examples: Input: arr[] = {-2, 6, 6, 3, 5, 4, 1, 2, 8}, K = 10Output: 3Explanation: All possible non-overlapping subarrays with sum K(= 10) are {-2, 6, 6}, {5, 4, 1}, {2,
    6 min read
  • Count unordered pairs of equal elements for all subarrays
    Given an array arr[] consisting of N integers, the task is to find the total number of unordered pairs (i, j) in the array such that arr[i] is equal to arr[j] and i < j for all subarrays of the given array. Examples: Input: arr[] = {1, 2, 1, 1}Output: 6Explanation: All subarrays of the given arra
    7 min read
  • 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: 1 Explanation: Only subarray {2, 10, 2, 10} satisfies the required condition. In
    9 min read
  • Maximum sum of lengths of non-overlapping subarrays with k as the max element.
    Find the maximum sum of lengths of non-overlapping subarrays (contiguous elements) with k as the maximum element. Examples: Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4} k = 4 Output : 5 {2, 1, 4} => Length = 3 {3, 4} => Length = 2 So, 3 + 2 = 5 is the answer Input : arr[] = {1, 2, 3, 2, 3, 4, 1
    15+ min read
  • Max sum of M non-overlapping subarrays of size K
    Given an array and two numbers M and K. We need to find the max sum of sums of M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array si
    15+ min read
  • Count maximum non-overlapping subarrays with given sum
    Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Expla
    7 min read
  • Count subarrays with all elements greater than K
    Given an array of n integers and an integer k, the task is to find the number of subarrays such that all elements in each subarray are greater than k. Examples: Input: arr[] = {3, 4, 5, 6, 7, 2, 10, 11}, k= 5 Output: 6 The possible subarrays are {6}, {7}, {6, 7}, {10}, {11} and {10, 11}. Input: arr[
    9 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences