Find power-of-two subarrays within sum range
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Find power-of-two subarrays within sum range states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= len(nums) <= 10^5
- nums[i] may be negative, zero, or positive
- k may be negative, zero, or positive; the range [k, 2k] is empty when k < 0 (since then 2k < k)
- Only subarray lengths that are exact powers of two (1, 2, 4, 8, ...) are considered
- Index ranges are 0-indexed and inclusive on both ends
Examples
Input: ([1, 2, 3, 4], 3)
Expected Output: [[2, 2], [3, 3], [0, 1], [1, 2]]
Explanation: Length-1 windows: nums[2]=3 and nums[3]=4 are in [3, 6]. Length-2 windows: [0,1] sums to 3 and [1,2] sums to 5, both in [3, 6]. Length-4 window sums to 10, out of range.
Input: ([5], 5)
Expected Output: [[0, 0]]
Explanation: Single-element array; the only power-of-two length is 1, and the sum 5 lies in [5, 10].
Hints
- Precompute prefix sums so any window sum is prefix[start+length] - prefix[start] in O(1).
- The only candidate lengths are powers of two; there are at most floor(log2(n)) + 1 of them, so iterate length = 1, 2, 4, ... up to n.
- For each length, slide the start from 0 to n - length and test whether the window sum falls in [k, 2k]. This handles negative values naturally — no monotonic sliding-window trick is required.
- Emit results ordered by length first, then by start index, to get a stable, predictable output.