1808. Balanced Scales Count

Hard7.5 points estimatedEnumerationHash TableRecursion

A balance scale has a left pan and a right pan. For each entry of weights you choose one of three things: put it on the left pan, put it on the right pan, or leave it off. Count the placements where both pans weigh exactly the same and at least one weight is on a pan. Placements are told apart by which pan or off-state each index gets, so equal weights at different indices and mirror images are all counted separately. Return the count as a long.

Trying 3^n placements is too slow. Split the weights into two halves, list the signed sum (left minus right) of every placement of each half, store the first half in a hash map of counts, and match each second-half sum with its negation. Subtract the single all-off placement at the end. Time and space about O(3^(n/2)).

Example 1

Input:
weights = [1,1]
Output:
2
Explanation:

One weight on each pan balances in two mirrored ways.

Example 2

Input:
weights = [1,2,3]
Output:
2
Explanation:

Weights 1 and 2 against 3, and the mirror image, give 2.

Example 3

Input:
weights = [5]
Output:
0
Explanation:

A single weight cannot balance by itself, so the answer is 0.

Constraints

1 ≤ n ≤ 24 (n = weights.length)

1 ≤ weights[i] ≤ 108

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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(3^(n/2))
Space
O(3^(n/2))

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…