Implement Integer Square Root
Company: J.P. Morgan
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates numerical algorithm design and integer arithmetic competence, including robustness for edge cases and overflow handling, and is categorized in the Coding & Algorithms domain.
Constraints
- 0 <= x <= 2147483647 (fits in a 32-bit signed integer)
- Do not use any built-in square root function or exponent/power operator
- Must not overflow: in Java/C++, compute mid * mid using a 64-bit type
Examples
Input: (4,)
Expected Output: 2
Explanation: 4 is a perfect square; floor(sqrt(4)) = 2.
Input: (8,)
Expected Output: 2
Explanation: sqrt(8) = 2.828..., integer part is 2.
Input: (0,)
Expected Output: 0
Explanation: Edge case: sqrt(0) = 0.
Input: (1,)
Expected Output: 1
Explanation: Edge case: sqrt(1) = 1.
Input: (2,)
Expected Output: 1
Explanation: Smallest non-perfect square > 1; floor(sqrt(2)) = 1.
Input: (9,)
Expected Output: 3
Explanation: Perfect square; floor(sqrt(9)) = 3.
Input: (15,)
Expected Output: 3
Explanation: sqrt(15) = 3.872..., integer part is 3 (just below the next perfect square 16).
Input: (16,)
Expected Output: 4
Explanation: Perfect square; floor(sqrt(16)) = 4.
Input: (2147483647,)
Expected Output: 46340
Explanation: Max 32-bit signed int; floor(sqrt(2147483647)) = 46340 (46341^2 overflows 32 bits).
Input: (2147395600,)
Expected Output: 46340
Explanation: 46340^2 exactly; tests the boundary where mid * mid must not overflow a 32-bit type.
Hints
- The answer lies in the range [0, x]. For x >= 2, the square root is at most x // 2, so you can search [1, x // 2].
- Binary search on the candidate answer: if mid * mid <= x, mid could be the answer (record it) and search higher; otherwise search lower.
- In languages with fixed-width integers, mid * mid can overflow 32 bits — cast to a 64-bit (long / long long) before multiplying.
- Follow-up: Newton's iteration r = (r + x // r) // 2 converges quadratically and is the more efficient practical method.