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

0% completed

Vote For New Content
O(X^{1/4}) solution

vladyslav.chikov

Nov 22, 2025

There is a solution which in terms of big-O notation is not that good as binary search, but good enough for the most of modern numbers.

The first instinct you want to go is:

class Solution:   def mySqrt(self, x: int) -> int:     i = 0     step = 1     while (i+1) * (i+1) <= x:       i += 1     return i

This algo is O(X^{1/2}) which is not bad and will work on any modern CPU all the way till 10^14-10^16

But you quickly realise that if your input is, say, 10**16, and you do i = 1, then likely do i=2,3,4,5 is pretty useless.

Instead we can do an incremental jump size too to increase the growth. Once we cross the bar, we slow down the growth until it stops:

class Solution:   def mySqrt(self, x: int) -> int:     i = 0     step = 1     while (i+step) * (i+step) <= x:       i += step       step += 1         while step > 0:       if (i+step) * (i+step) > x:         step -= 1       else:         i += 1     return i

This solution is quadratic root of X, and it is not the most perfect still, for 10^1000 the binary search is unbelievably better, but for 10**12 it will do the job in just 1000+~tail of operations, but not exceeding 2000.

0

0

Comments
Comments

On this page

Problem Statement

Try it yourself