Find the largest integer whose square does not exceed x. The Last True pattern — condition is true for small values and flips false for large ones.
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. You must not use any built-in exponent or sqrt functions. Must run in O(log x).
The condition mid * mid <= x is true for small values of mid and false for large values. This is the reverse of First True — the boolean pattern is T T T T F F F and we want the last T.
Last True vs First True: in First True when the condition is true we move the right pointer left to find an earlier true. In Last True when the condition is true we move the left pointer right to find a later true. The boundary variable always saves the current best answer.
Overflow danger in Java: mid * mid can overflow int when x is close to Integer.MAX_VALUE (~2.1 billion). Cast mid to long before squaring. In Python, integers have arbitrary precision so this is never an issue.
x = 8, answer = 2
16 <= 8? No → condition FALSE. Go left: right=3.
4 <= 8? Yes → condition TRUE. Save boundary=2, go right: left=3.
9 <= 8? No → condition FALSE. Go left: right=2.
Return boundary=2. ✓
class Solution { public int mySqrt(int x) { if (x == 0) return 0; int left = 1, right = x, boundary = 1; while (left <= right) { long mid = left + (long)(right - left) / 2; // long to avoid overflow if (mid * mid <= x) { // condition TRUE: valid floor sqrt — save and search right for larger boundary = (int) mid; left = (int) mid + 1; } else { // condition FALSE: too large, go left right = (int) mid - 1; } } return boundary; } }
class Solution: def mySqrt(self, x: int) -> int: if x == 0: return 0 left, right, boundary = 1, x, 1 while left <= right: mid = left + (right - left) // 2 if mid * mid <= x: # condition TRUE: valid — save and search right for larger boundary = mid left = mid + 1 else: # condition FALSE: too large, go left right = mid - 1 return boundary
Last True template difference from First True: The only change is the direction we move when the condition is true. First True: right = mid - 1. Last True: left = mid + 1. Everything else — the loop condition, the boundary variable, the false branch — is identical.