← Questions

Count index pairs with an even product and odd distance

0
GoogleCodingLast asked Jan 2025

A coding interview question asked in Google's first round (coding), last asked Jan 2025. It tests arrays and counting.

Given an integer array, count the index pairs i < j where nums[i] * nums[j] is even and j - i is odd. Do it without checking every pair.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_special_pairs(nums: list[int]) -> int — values may be negative or zero (zero is even).

Example

count_special_pairs([1, 2, 3, 4])      ->  4    # (0,1), (0,3), (1,2), (2,3)
count_special_pairs([1, 3, 5])         ->  0    # every product is odd
count_special_pairs([2, 2, 2, 2, 2])   ->  6    # 3 even indices x 2 odd indices
count_special_pairs([1, 3, 2, 5, 7])   ->  2    # only pairs with the 2 at index 2 work
count_special_pairs([0, -3])           ->  1
count_special_pairs([])                ->  0

Constraints

  • 0 <= n <= 10^6; the count can reach about n^2 / 4, so use 64-bit integers.
  • O(n) time, O(1) space.

Clarifying questions

  • Can values be negative or zero, and is zero even?
  • How large is n, and can the answer overflow 32 bits?
  • Count pairs or list them?
  • Is an O(n) solution expected?

What a strong answer covers

  • j - i is odd exactly when i and j have different parity, so every valid pair joins an even index with an odd index.
  • A product is even unless both values are odd. So the answer is (even indices × odd indices) minus (odd values at even indices × odd values at odd indices).
  • Four counters in one pass, O(n) time, O(1) space; or a one-pass version that adds, at each j, the qualifying earlier indices of the other parity.
  • Why the subtraction doesn't double count.
  • Tests: empty, one element, all odd, all even, zeros and negatives.

Follow-ups

  • Count pairs with an even distance instead.
  • Count pairs where the product is odd.
  • Indices arrive as a stream; keep the count current.

Where it's asked

  • Google · First round: coding · Last asked Jan 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

arrays · counting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding