← Questions

Subarrays with power-of-two length and sum between K and 2K

0
MetaCodingLast asked Aug 2025

A coding interview question asked in Meta's technical phone screen, last asked Aug 2025. It tests prefix sums and arrays.

Given an integer array nums and an integer k, find every contiguous subarray whose length is a power of two (1, 2, 4, 8, ...) and whose sum lies between k and 2k, inclusive. Return their index ranges.

Interface

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

  • power_of_two_subarrays(nums: list[int], k: int) -> list[list[int]] — [start, end] pairs, 0-based and inclusive. Ordered by length first, then by start index.

Example

power_of_two_subarrays([1, 2, 3, 4], 3)     ->  [[2, 2], [3, 3], [0, 1], [1, 2]]
    # length 1: 3 and 4 lie in [3, 6]; length 2: 1+2 = 3 and 2+3 = 5; length 4: 10 is too big
power_of_two_subarrays([4, -1, 2, 5], 3)    ->  [[0, 0], [3, 3], [0, 1]]
power_of_two_subarrays([5], 5)              ->  [[0, 0]]
power_of_two_subarrays([], 1)               ->  []

Constraints

  • 0 <= len(nums) <= 10^5. Values may be negative, zero or positive.
  • If k < 0, the range [k, 2k] is empty and nothing matches.
  • Faster than O(n²).

Clarifying questions

  • Is the range inclusive at both ends?
  • Can values be negative? Can k be negative or zero?
  • Return the ranges, or only how many there are?
  • Is a length-1 subarray a power of two? (Yes, 2⁰.)

What a strong answer covers

  • Only about log₂(n) lengths are possible. For each, check every window.
  • Prefix sums give each window's sum in O(1), so the whole scan is O(n log n) time and O(n) space. A rolling sum per length works too.
  • Why this beats checking all O(n²) subarrays, and that the output itself can be O(n log n) long.
  • Handling negative values: prefix sums do not rely on sums growing with length, unlike a two-pointer window.
  • Tests: an empty array, negative k, negative values, a length equal to the whole array.

Follow-ups

  • Count the matches only. With non-negative values, can you avoid listing them?
  • The length may be any value, not just a power of two: count subarrays with sum in [k, 2k] using prefix sums and a sorted structure.
  • Report only the longest matching subarray.

Where it's asked

  • Meta · Technical phone screen · Last asked Aug 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

prefix sums · arrays

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