1531. Fake Coin Weighings

Easy1.5 points estimatedBrainteaserMaths

A mint has n coins that look identical. Exactly one of them is slightly heavier than the others. You have a two-pan balance scale with no weights. Each weighing puts some coins on the left pan and some on the right, and the scale tells you whether the left side is heavier, the right side is heavier, or they balance.

Return the minimum number of weighings that is always enough to identify the heavy coin, whatever it turns out to be. Each weighing can split the remaining suspects into three groups (left heavy, right heavy, balanced), so count how many weighings are needed until every group can be reduced to a single coin. When n is 1, no weighing is needed and the answer is 0.

Input: one integer n. Output: one integer. Aim for O(log n) time and O(1) space; beware that the powers of three exceed 32 bits.

Example 1

Input:
n = 9
Output:
2
Explanation:

Three weighings are not needed: 3^2 = 9 covers nine coins, so two weighings suffice.

Example 2

Input:
n = 10
Output:
3
Explanation:

Nine coins fit in two weighings, but ten need a third.

Constraints

1 ≤ n ≤ 1015

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

Expected complexity

Time
O(log n)
Space
O(1)

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…