Sitemap

CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Member-only story

πŸ§‘β€πŸ’» LeetCode 0069 β€” Sqrt(x), All Solutions Explained with Java! 🧠

--

https://github.com/nphausg/leetcode.solution/blob/main/src/com/nphausg/leetcode/utils/sqrt_method_comparison.ipynb

β€œThe journey of a thousand miles begins with one step… or one square root.”

πŸ” Problem Overview

Given a non-negative integer x, compute and return the square root of x, rounded down to the nearest integer. You must not use any built-in exponent function or operator like Math.sqrt() or x ** 0.5.

Example:

Input: x = 8
Output: 2
Explanation: sqrt(8) β‰ˆ 2.828, so we return 2.

πŸ› οΈ Solution 1: Brute Force (Linear Search) 🐒

Idea

Try all integers i starting from 0. Stop when i * i > x. The previous i will be the answer.

public int mySqrt(int x) {
if (x < 2) return x;

for (int i = 1; i <= x / 2; i++) {
if (i <= x / i && (i + 1) > x / (i + 1)) {
return i;
}
}
return 1;
}

⏱️ Time Complexity:

  • O(√x) β€” Worst case for very large x.

πŸ—‚οΈ Space Complexity:

  • O(1) β€” Only constant extra space.

⚠️ Drawback:

  • Not efficient for very large values of x.

⚑ Solution 2: Binary…

--

--

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Leo N
Leo N

Written by Leo N

πŸ‡»πŸ‡³ πŸ‡ΈπŸ‡¬ πŸ‡²πŸ‡Ύ πŸ‡¦πŸ‡Ί πŸ‡ΉπŸ‡­ Engineer @ GXS Bank, Singapore | MSc πŸŽ“ | Technical Writer . https://github.com/nphausg

No responses yet