You get a positive whole number num. Return true if it is a perfect square, meaning some whole number multiplied by itself gives exactly num, and false otherwise.
Do not call a built-in square root or power function. The point is to find the answer with plain arithmetic.
Example 1
Input: num = 49 Output: true Why: 7 × 7 = 49
2 more examples and the constraints
Example 2
Input: num = 50 Output: false Why: 7 × 7 = 49 is too small and 8 × 8 = 64 too big
Example 3
Input: num = 1 Output: true Why: 1 × 1 = 1
Constraints
- 1 ≤ num ≤ 2,147,483,647 (2³¹ − 1)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count upO(√n)
- Binary search on the rootO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for num = 2,147,483,647 | Verdict |
|---|---|---|---|
| Count up | O(√n) | Passes; about 46,000 tries | |
| Binary search on the root | O(log n) | Best; about 31 tries |
n = num.
Edge cases to test
- num = 1. It is 1 × 1, so the answer is
true; the search range starts and ends at 1. - The largest input. 2,147,483,647 is not a square. Squaring a mid near a billion overflows 32-bit integers.
- Largest square in range. 46,340² = 2,147,395,600 must return
true; one less must returnfalse. - Just below a square. 999,999 sits right under 1,000²: the search ends with lo one above hi.
Common mistakes
- Computing mid * mid in a 32-bit int, which overflows and gives wrong comparisons.
- Using a floating-point square root and comparing, which the problem forbids and which can round wrong for big numbers.
- Writing
while lo < hiand returning before checking the last candidate.
How to talk through it
- 1Clarify. Is num always positive? Is a built-in square root off limits? How large can it get?
- 2Give the count-up loop. Try 1, 2, 3, … until the square passes num: O(√n), about 46,000 steps at worst.
- 3Name the order. A bigger root gives a bigger square, so each guess tells you which half to keep.
- 4Code the binary search. Search 1 to num, square mid in 64 bits, move lo or hi past mid.
- 5Test out loud. Run 1, 50 and 2,147,483,647 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?