← All Lessons Lesson 47 / 68
Lesson 47

Counting Even and Odd Numbers in Every Window of Size k

The Problem

You are given a list of whole numbers, called arr, and a positive number k. Your job is to look at every block of k numbers that sit next to each other in the list, and for each block, count how many numbers are even and how many are odd.

A block of numbers that sit next to each other is called a subarray. When the block always has the same fixed size k and we keep sliding it one step to the right, people often call it a window of size k.

A quick reminder: even vs odd

  • An even number can be split into two equal halves with nothing left over: 4, 0, 2.
  • An odd number always has one left over: 1, 5, 3.
  • The simple test in code: a number x is even when x % 2 == 0, and odd otherwise. The % symbol gives the remainder after division.

Walking through Example 1

arr = [4, 4, 5, 1, 4], k = 3

We slide a window of size 3 from left to right. Each time, we count evens and then odds.

  1. First window: [4, 4, 5] → evens are 4, 4 (count 2), odd is 5 (count 1) → [2, 1]
  2. Slide one step right: [4, 5, 1] → even is 4 (count 1), odds are 5, 1 (count 2) → [1, 2]
  3. Slide again: [5, 1, 4] → even is 4 (count 1), odds are 5, 1 (count 2) → [1, 2]

So the answer is [[2, 1], [1, 2], [1, 2]]. Each small pair gives even count first, odd count second.

Notice we stop here. With 5 numbers and a window of size 3, there are only 3 places the window can sit. In general, the number of windows is arr.length - k + 1, which is 5 - 3 + 1 = 3.

Example 2 (the easy edge case)

arr = [1, 2, 3, 5], k = 1

When k = 1, every window is just a single number. So each result is either [0, 1] (the number is odd) or [1, 0] (the number is even):

  • 1 is odd → [0, 1]
  • 2 is even → [1, 0]
  • 3 is odd → [0, 1]
  • 5 is odd → [0, 1]

Result: [[0, 1], [1, 0], [0, 1], [0, 1]].

How you would solve it

The straightforward idea: for each starting position, count fresh.

  1. Loop the start position i from 0 up to arr.length - k.
  2. For each start, look at the k numbers from i to i + k - 1.
  3. Count evens and odds in that block, and store the pair.

This works fine. A smarter version (the sliding window trick) avoids recounting everything: when the window slides one step, you only remove the number that left on the left and add the new number on the right, updating the counts as you go. That makes it much faster for big lists.

The function returns a list of pairs, which matches the C++ signature on the page: vector<pair<int, int>> evenOddCount(...). Each pair holds the two counts: even first, odd second.

Counting Even and Odd Numbers in Every Window of Size k
Diagram — click to zoom (scroll / drag to pan)