Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
 Jlsegb
Most performant solution

Jlsegb

Jan 27, 2026

You can ask an LLM to explain it. But this is a neat way of calculating a root. Probably better to use the binary tree solution but this one performs better O(log log n)

class Solution { public: int mySqrt(int x) { if (x == 0) return 0; int r = x; while (r > x / r) { // instead of r*r > x r = (r + x / r) / 2; // this is Newton's method. } return (int)r; // floor(sqrt(x)) } };

Note that we should avoid a possible integer overflow from r*r by re-arranging the equality or using a bigger container.

0

0

Comments

On this page

Problem Statement

Try it yourself