Bird
Raised Fist0
Interview Prepmodified-binary-searcheasyAmazonGoogleBloomberg

Sqrt(x) - Integer Square Root

Choose your preparation mode4 modes available
📋
Problem

Imagine you are designing a calculator app that needs to quickly find the integer square root of a large number without using built-in functions.

Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. You must not use any built-in exponent function or operator.

0 ≤ x ≤ 2^31 - 1
Edge cases: x = 0 → output 0x = 1 → output 1x = 2147395599 (just below 46340^2) → output 46339
</>
IDE
def mySqrt(x: int) -> int:public int mySqrt(int x)int mySqrt(int x)function mySqrt(x)
def mySqrt(x: int) -> int:
    # Write your solution here
    pass
class Solution {
    public int mySqrt(int x) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int mySqrt(int x) {
    // Write your solution here
    return 0;
}
function mySqrt(x) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Too large (e.g., 46340 for input 2147395599)Overflow in mid*mid calculation causing incorrect comparisons.✅ Cast mid to 64-bit integer before multiplication to avoid overflow.
Wrong: Off-by-one low (e.g., 1 for input 4)Not returning mid when mid*mid == x; binary search boundaries updated incorrectly.✅ Add condition to return mid immediately if mid*mid == x.
Wrong: Non-zero for input 0Missing base case for x=0; loop or binary search assumes x>0.✅ Add explicit check: if x == 0 return 0.
Wrong: Too slow or timeout on large inputUsing brute force linear search instead of binary search.✅ Implement binary search to reduce time complexity to O(log x).
✓
Test Cases
t1_01basic
Input{"x":8}
Expected2

The square root of 8 is approximately 2.82842, truncating decimal part gives 2.

t1_02basic
Input{"x":15}
Expected3

Square root of 15 is about 3.8729, truncating decimal part gives 3.

t2_01edge
Input{"x":0}
Expected0

Square root of 0 is 0.

t2_02edge
Input{"x":1}
Expected1

Square root of 1 is 1.

t2_03edge
Input{"x":2147395599}
Expected46339

2147395599 is just below 46340^2; integer sqrt truncates to 46339.

t3_01corner
Input{"x":2147483647}
Expected46340

Maximum 32-bit int; sqrt truncates to 46340.

t3_02corner
Input{"x":4}
Expected2

Square root of 4 is exactly 2; tests exact boundary condition.

t3_03corner
Input{"x":9}
Expected3

Square root of 9 is exactly 3; tests off-by-one errors in binary search.

t4_01performance
Input{"x":2147483647}
⏱ Performance - must finish in 2000ms

Maximum input value x=2^31-1; binary search O(log x) must complete within 2 seconds.

Practice

(1/5)
1. You are given an unsorted array of integers and need to find an index of an element that is greater than its neighbors (or boundary elements if at edges). Which algorithmic approach guarantees an optimal O(log n) time solution for this problem?
easy
A. Linear scan checking each element and its neighbors sequentially
B. Dynamic programming to store and compare local maxima
C. Modified binary search that compares middle element with its right neighbor to decide search direction
D. Greedy approach selecting the first element larger than the previous one

Solution

  1. Step 1: Understand problem constraints

    The problem requires finding a peak element efficiently, which suggests a logarithmic time approach.
  2. Step 2: Identify algorithm matching O(log n) time

    Modified binary search that compares mid element with its neighbor to decide which half to search next achieves O(log n) time.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Binary search halves search space each step [OK]
Hint: Peak element search uses modified binary search [OK]
Common Mistakes:
  • Assuming greedy or DP solves this optimally
  • Confusing linear scan as optimal
  • Using DP unnecessarily
2. You are given an array representing the days on which flowers bloom. You want to make m bouquets, each consisting of k adjacent flowers. What is the most efficient approach to find the minimum day by which you can make all bouquets?
easy
A. Apply binary search on the range of days and check feasibility for each mid value.
B. Use a greedy approach to pick the earliest blooming flowers until bouquets are formed.
C. Use dynamic programming to track the minimum days for each bouquet count.
D. Sort the bloom days and pick the first m*k flowers directly.

Solution

  1. Step 1: Understand the problem constraints

    We need to find the minimum day such that we can form m bouquets of k adjacent flowers. The days range from min to max bloom day.
  2. Step 2: Recognize the pattern

    Binary searching over the answer space (days) and checking feasibility for each candidate day efficiently narrows down the minimum day. Greedy or sorting alone do not guarantee correctness because adjacency and feasibility must be checked.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary search on answer space is the standard pattern for such minimum day feasibility problems. [OK]
Hint: Binary search on answer space fits minimum day feasibility problems [OK]
Common Mistakes:
  • Thinking greedy or sorting alone solves adjacency constraints
  • Using DP unnecessarily complicates the problem
3. Examine the following buggy code for finding the single non-duplicate element in a sorted array. Which line contains the subtle bug that can cause incorrect results or infinite loops?
medium
A. Line 11: updating high to mid - 1 may skip the single element
B. Line 5: parity check on mid is incorrect for odd indices
C. Line 7: comparison with nums[mid + 1] can cause index out of range
D. Line 3: mid calculation uses division without floor, resulting in float index

Solution

  1. Step 1: Identify mid calculation issue

    Using '/' in Python 3 returns float, which cannot index arrays, causing errors or infinite loops.
  2. Step 2: Confirm other lines are correct

    Parity checks and updates are correct; no out-of-range access due to loop conditions.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    mid must be integer index; float causes failure [OK]
Hint: mid must be integer index, not float [OK]
Common Mistakes:
  • Using '/' instead of '//' in Python 3
  • Confusing parity logic
  • Incorrect boundary updates
4. Suppose the problem is modified so that the matrix rows are sorted but columns are not guaranteed to be sorted. Which approach would correctly find the kth smallest element efficiently?
hard
A. Use the min-heap approach merging rows as before, since rows remain sorted.
B. Flatten the matrix and sort it, then return the kth element.
C. Use binary search on the value range with a counting function scanning the entire matrix.
D. Use a min-heap merging columns instead of rows.

Solution

  1. Step 1: Analyze matrix properties

    Rows are sorted but columns are not, so min-heap merging rows only partially orders elements.
  2. Step 2: Evaluate approaches

    Min-heap merging rows assumes columns sorted for correctness; binary search counting requires sorted rows and columns for efficient counting; flatten and sort works regardless.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Flatten and sort is the fallback when only rows sorted [OK]
Hint: Partial sorting breaks heap and binary search assumptions [OK]
Common Mistakes:
  • Assuming min-heap merging rows still works
  • Using binary search counting without full sorting
  • Ignoring matrix sorting properties
5. Suppose the problem is modified so that balls can be placed multiple times at the same position (reuse allowed). Which modification to the algorithm is correct to find the maximum minimum distance?
hard
A. Keep the same binary search and greedy feasibility check since reuse does not affect placement logic
B. Modify feasibility check to count balls without updating last_pos when reuse occurs
C. Replace binary search with a linear search over all distances due to reuse complexity
D. Use dynamic programming to handle multiple placements at the same position

Solution

  1. Step 1: Understand reuse impact

    Allowing reuse means multiple balls can be placed at the same position, so distance between balls can be zero.
  2. Step 2: Modify feasibility check

    The greedy check must count balls even if distance is zero, but only update last_pos when distance condition is met to avoid infinite loops.
  3. Step 3: Binary search remains valid

    Binary search on answer space still applies, but feasibility check logic must adapt to reuse.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Feasibility check must handle reuse carefully [OK]
Hint: Reuse breaks distance check; feasibility must count balls differently [OK]
Common Mistakes:
  • Assuming reuse doesn't change feasibility check
  • Switching to linear search unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard