Ctrl K

Squaring Ladder

Medium
You are given an integer array values. Call a set of its elements (not necessarily adjacent) a *ladder* if, once sorted in increasing order, every number except the first is the square of the one before it. For example, [2, 4, 16] is a ladder. A ladder must contain at least two numbers. Return the length of the longest ladder you can build from the array's elements, or -1 if no ladder exists.
Example 1
values=[9, 5, 81, 3, 25, 7] → 3

Take 3, 9 and 81: 9 = 3² and 81 = 9². The chain 5 → 25 is shorter.

Example 2
values=[10, 11, 12] → -1

No number is the square of another, so there is no ladder.

Example 3
values=[4, 2, 4] → 2

The ladder is 2 → 4; the second 4 does not make it longer.

Constraints
  • 2 ≤ len(values) ≤ 10⁵
  • 2 ≤ values[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWords Hidden in a Text MediumShuttle Driver Earnings MediumSell Plots to Bidders MediumSpells Without Neighbors MediumClimbing Along Rows and Columns Hard
loading Python…
Input
values=[9, 5, 81, 3, 25, 7]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 55 tests on the server, hidden ones included.