Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: The function below should return the integer square root ⌊√x⌋.

Problem: The function below should return the integer square root ⌊√x⌋.
static int isqrt(int x) {
    int lo = 0, hi = x, ans = 0;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if ((long) mid * mid <= x) { ans = mid; lo = mid + 1; }
        else hi = mid - 1;
    }
    return ans;
}
// isqrt(26) + " " + isqrt(1) + " " + isqrt(2147395600)
What does the commented expression evaluate to?
  1. A. 5 1 46340
  2. B. 5 1 46341
  3. C. 6 1 46340
  4. D. 5 0 46340

Correct answer: A. 5 1 46340

Keep the last mid whose square fits. 5² = 25 ≤ 26 < 36. 2147395600 = 46340² exactly. The (long) cast matters: mid * mid in int overflows for mid near 46341 and the search would go wrong. O(log x).

More Coding Interview Problems questions

Exams that ask this topic