1239. Power Total Stretches

A cashier tracks the net change in the till after each customer, stored in the integer array nums. The manager considers a stretch of consecutive customers round when its net change is a power of two: 1, 2, 4, 8 and so on. Zero and negative totals are never powers of two.

Return how many non-empty contiguous stretches have a total that is a power of two, as a long. Stretches at different positions are counted separately. Every subarray total stays below 2^30 in absolute value, so only the powers 2^0 through 2^30 need to be tested. For each prefix sum P, look up P minus each of those powers in a hash map holding the counts of earlier prefix sums.

The intended solution runs in O(31 * n) time and O(n) space.

Example 1

Input:
nums = [5,-3,6,2,-7,9,4,1,-2]
Output:
11
Explanation:

Eleven stretches total a power of two, for example [5, -3] totals 2, [5, -3, 6] totals 8 and the whole array totals 16.

Example 2

Input:
nums = [12,-4,0,8,-8,3,5]
Output:
12
Explanation:

Twelve stretches total a power of two, for example [12, -4] totals 8, [12, -4, 0, 8] totals 16 and the lone 8 at index 3 totals 8.

Constraints

1 ≤ nums.length ≤ 105

-104 ≤ nums[i] ≤ 104 (so every subarray sum is below 230 in absolute value)

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(31 * n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…