Magicsheet logo

Count Subarrays of Length Three With a Condition

Easy
95.6%
Updated 6/1/2025

Topics

Count Subarrays of Length Three With a Condition

What is this problem about?

The "Count Subarrays of Length Three With a Condition interview question" is a fixed-size window problem. You are given an array of integers and need to count how many contiguous subarrays of length exactly three satisfy a specific condition (for example, the first and third elements are equal, or the sum matches a target). This is an introductory array challenge focused on window traversal.

Why is this asked in interviews?

Microsoft and Meta ask the "Count Subarrays of Length Three coding problem" to evaluate a candidate's basic loop control and array indexing. It’s a warm-up question that ensures you can handle boundaries (not going out of index) and correctly extract segments of a specific length. It checks for clean, concise coding in the "Array interview pattern" category.

Algorithmic pattern used

This problem follows the Sliding Window (Fixed Size) pattern.

  1. Linear Loop: Iterate through the array from index 0 up to n3n - 3.
  2. Window Extraction: For each index ii, consider the elements at i,i+1i, i+1, and i+2i+2.
  3. Condition Check: Apply the logic required by the problem (e.g., arr[i] == arr[i+2]).
  4. Count: Increment a counter for every match found.

Example explanation

Array: [1, 2, 1, 3, 1], Condition: arr[i] == arr[i+2]

  • i=0: [1, 2, 1]. 1==11 == 1. (Count = 1)
  • i=1: [2, 1, 3]. 2eq32 eq 3.
  • i=2: [1, 3, 1]. 1==11 == 1. (Count = 2) Result: 2.

Common mistakes candidates make

  • Index Out of Bounds: Forgetting to stop the loop at n3n-3, causing the code to look for i+2i+2 beyond the array end.
  • Confusion with Subsequences: Treating the problem as if the elements don't need to be adjacent.
  • Incorrect Length: Using a window of size 2 or 4 instead of 3.

Interview preparation tip

When a problem specifies a small fixed length (like 3), a simple loop with direct index access is often better and faster to write than a general-purpose sliding window implementation. Keep it simple and focus on boundary correctness.

Similar Questions