Notes
All notes

Math and Geometry (LeetCode #18)

The last technique is a toolbox: rotate and traverse matrices in place, use the input as \(O(1)\) memory, detect a repeated state with Floyd’s algorithm, raise to a power by halving the exponent, and simulate arithmetic on strings and coordinates. This post covers all 8 NeetCode Math & Geometry problems.

The technique

Four ideas to reuse: in-place matrix rotation (ring by ring), boundary traversal (shrink four boundaries), marking with the input, and fast exponentiation (\(x^n = (x^{n/2})^2\)).

Rotate Image

The question. Rotate an n × n matrix 90° clockwise in place.

Input:  [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

The idea. The four cells (i,j) → (j,n-1-i) → (n-1-i,n-1-j) → (n-1-j,i) cycle. Move each ring’s cells around the cycle.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \node[c, fill=blue!8] (a) at (0,0.9) {1}; \node[c, fill=blue!8] (b) at (0.9,0.9) {3};
  \node[c, fill=blue!8] (c) at (0.9,0) {9}; \node[c, fill=blue!8] (d) at (0,0) {7};
  \draw[->, thick, orange!80!black] (a) -- (b);
  \draw[->, thick, orange!80!black] (b) -- (c);
  \draw[->, thick, orange!80!black] (c) -- (d);
  \draw[->, thick, orange!80!black] (d) -- (a);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.45,-0.4) {each orbit is a 4-cycle};
\end{tikzpicture}

Walk it through the outer ring of [[1,2,3],[4,5,6],[7,8,9]] (i = 0, j = 0 then j = 1):

(i,j) a=m[i][j] b=m[n-1-j][i] c=m[n-1-i][n-1-j] d=m[j][n-1-i] writes
(0,0) 1 7 9 3 m[0][0]=7, m[2][0]=9, m[2][2]=3, m[0][2]=1
(0,1) 2 4 8 6 m[0][1]=4, m[1][0]=8, m[2][1]=6, m[1][2]=2

The center 5 is untouched (odd-sized matrices have a fixed middle). Result [[7,4,1],[8,5,2],[9,6,3]].

def rotate(matrix):
    n = len(matrix)
    for i in range(n // 2):
        for j in range(i, n - 1 - i):
            a = matrix[i][j]
            b = matrix[n-1-j][i]
            c = matrix[n-1-i][n-1-j]
            d = matrix[j][n-1-i]
            matrix[i][j] = b
            matrix[n-1-j][i] = c
            matrix[n-1-i][n-1-j] = d
            matrix[j][n-1-i] = a

Why these four indices. A 90° clockwise rotation sends row i, column j to row j, column n-1-i; applying the map four times returns to start, so each orbit has exactly four cells (except the center). The loops visit rings 0..n//2-1 and, within a ring, the top edge j ∈ [i, n-1-i) — every orbit has one top-edge representative, so each is moved exactly once.

Complexity. \(O(n^2)\) time, \(O(1)\) space. Simpler equivalent: transpose, then reverse each row.

Edge cases. \(1 \times 1\) → unchanged. The input is square by the problem’s guarantee.

Spiral Matrix

The question. Return all elements in spiral order.

The idea. Four boundaries top, bottom, left, right; traverse each edge, shrink the matching boundary, and guard the final row/column for non-square matrices.

Walk it through on [[1,2,3],[4,5,6],[7,8,9]]:

pass traversal output so far boundaries after
top row 1, 2, 3 1,2,3 top = 1
right col 6, 9 1,2,3,6,9 right = 1
bottom row ← 8, 7 …,8,7 bottom = 1
left col ↑ 4 …,4 left = 1
top row 5 …,5 top = 2 > bottom → stop

Result [1,2,3,6,9,8,7,4,5].

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.55cm, minimum height=0.5cm, font=\scriptsize\ttfamily}]
  \foreach \v/\x/\y in {1/0/0,2/1/0,3/2/0,6/2/1,9/2/2,8/1/2,7/0/2,4/0/1,5/1/1} { \node[c, fill=blue!8] at (\x*0.61,-\y*0.56) {\v}; }
  \draw[->, very thick, green!55!black] (0,0.35) -- (1.22,0.35) -- (1.22,-1.12) -- (0,-1.12) -- (0,-0.56) -- (0.61,-0.56);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.61,-1.7) {peel one layer per loop};
\end{tikzpicture}
def spiral_order(matrix):
    out = []
    top, bottom, left, right = 0, len(matrix)-1, 0, len(matrix[0])-1
    while top <= bottom and left <= right:
        for c in range(left, right + 1): out.append(matrix[top][c])
        top += 1
        for r in range(top, bottom + 1): out.append(matrix[r][right])
        right -= 1
        if top <= bottom:
            for c in range(right, left - 1, -1): out.append(matrix[bottom][c])
            bottom -= 1
        if left <= right:
            for r in range(bottom, top - 1, -1): out.append(matrix[r][left])
            left += 1
    return out

Why the two if guards. After the top edge and right edge are consumed, a single remaining row or column must be traversed exactly once — without the guards the bottom row would repeat a row already emitted (e.g. a tall single column), and vice versa.

Complexity. \(O(mn)\) time and output space, \(O(1)\) extra.

Edge cases. Single row → only the first loop body matters. Single column → only right edge. Empty matrix needs a guard before taking matrix[0].

Set Matrix Zeroes

The question. If a cell is 0, zero its row and column, in place.

The idea. Use the first row and column as flags for “this column/row must be zeroed”, remembering separately whether the first row/column themselves need zeroing, and applying that last.

Walk it through on [[1,1,1],[1,0,1],[1,1,1]]:

  1. No zero in row 0 or column 0, so first_row = first_col = False.
  2. Mark: interior zero at (1,1) sets flags matrix[1][0] = 0 (row 1) and matrix[0][1] = 0 (column 1).
  3. Zero pass: row 1 has its row flag, so the whole row goes; (2,1) has the column flag, so it goes; (2,2) has neither flag and survives. first_row/first_col are false, so nothing more changes.
1 1 1      1 0 1      1 0 1
1 0 1  ->  0 0 0  ->  0 0 0
1 1 1      1 0 1      1 0 1
def set_zeroes(matrix):
    rows, cols = len(matrix), len(matrix[0])
    first_row = any(matrix[0][c] == 0 for c in range(cols))
    first_col = any(matrix[r][0] == 0 for r in range(rows))
    for r in range(1, rows):
        for c in range(1, cols):
            if matrix[r][c] == 0:
                matrix[r][0] = 0
                matrix[0][c] = 0
    for r in range(1, rows):
        for c in range(1, cols):
            if matrix[r][0] == 0 or matrix[0][c] == 0:
                matrix[r][c] = 0
    if first_row:
        for c in range(cols): matrix[0][c] = 0
    if first_col:
        for r in range(rows): matrix[r][0] = 0

Why the first row/column are read last. They double as the flag storage, so marking overwrites them; the saved booleans preserve their own fate and are applied after every interior cell is decided.

Why marking and zeroing are separate passes. Zeroing while scanning would create new “original” zeroes that poison the flags; the mark pass only reads the interior and writes the flags, and the zero pass only reads the flags.

Complexity. \(O(mn)\) time, \(O(1)\) space.

Edge cases. A zero in the first row or column only sets the saved flag, not the whole flag line. Single-row/column matrices reduce to the flag logic.

Happy Number

The question. Repeatedly replace n with the sum of the squares of its digits. Happy if it reaches 1; otherwise it loops.

The idea. Detect the loop with Floyd’s fast/slow pointers (or a set).

Walk it through on n = 19: 19 → 82 → 68 → 100 → 1.

step slow fast (two jumps) fast == 1?
0 19 82 no
1 82 100 no
2 68 1 yes → happy

fast starts one jump ahead, so on n = 2 the pointers converge inside the cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 … (slow == fast) while fast never hits 1 → unhappy.

def is_happy(n):
    def square_sum(x):
        total = 0
        while x:
            x, d = divmod(x, 10)
            total += d * d
        return total
    slow, fast = n, square_sum(n)
    while fast != 1 and slow != fast:
        slow = square_sum(slow)
        fast = square_sum(square_sum(fast))
    return fast == 1

Why it must terminate. The digit-square sum of any number lands below \(9^2 \times\) digits (at most a few hundred), so the sequence from any start is eventually periodic; fast (two steps) then laps slow exactly as in linked-list cycle detection.

Why Floyd instead of a set. Both detect the repeat, but the two pointers need \(O(1)\) space versus the set’s \(O(\text{cycle length})\).

Complexity. \(O(\log n)\) per step (digits), \(O(1)\) space.

Edge cases. n = 1 → True (fast starts at 1, loop skipped). Powers of 10 collapse to 1 in one or two steps.

Plus One

The question. A big non-negative integer is stored as digit array; add 1 and return the new digits.

Input:  [1,2,3]  ->  [1,2,4]
Input:  [9,9,9]  ->  [1,0,0,0]

The idea. Add from the right, carrying. Set a digit to 0 when it is 9 and carry continues; stop at the first digit < 9. If the carry survives every digit, prepend a 1.

Walk it through on [1,2,9]: last is 9 → 0, carry; next is 2 → 3, stop → [1,3,0]. On [9,9,9]: all become 0, carry survives → [1,0,0,0].

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \node[c, fill=blue!8] at (0,0) {1}; \node[c, fill=orange!20] at (0.66,0) {2}; \node[c, fill=orange!20] at (1.32,0) {9};
  \draw[->, thick, orange!80!black] (1.32,0.28) -- (0.66,0.28);
  \node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=south] at (0.99,0.35) {carry};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.66,-0.4) {9s flip, first smaller digit absorbs it};
\end{tikzpicture}
def plus_one(digits):
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            return digits
        digits[i] = 0
    return [1] + digits

\(O(n)\) time, \(O(1)\) extra space (except the all-9s case).

Pow(x, n)

The question. Compute \(x^n\) (n can be negative).

The idea. Halve the exponent: square the base each step, and multiply it into the result whenever the current exponent bit is 1.

Walk it through on x = 2, n = 10 (10 = 1010₂):

n (binary) lowest bit action result x next
10 (1010) 0 skip 1 4
5 (101) 1 result ×= 4 4 16
2 (10) 0 skip 4 256
1 (1) 1 result ×= 256 1024 —

\(`4 × 256 = 2^{2} × 2^{8} = 2^{10}\)` — the set bits select exactly the needed squares.

def my_pow(x, n):
    if n < 0:
        x, n = 1 / x, -n
    result = 1.0
    while n:
        if n & 1:
            result *= x
        x *= x
        n >>= 1
    return result

Why squaring works. \(x^{n}\) factors by the binary expansion of n: each bit position i contributes \(x^{2^i}\) only if set, and x *= x builds exactly those successive squares. Negative n is handled up front by reciprocating.

Complexity. \(O(\log n)\) time (one step per bit), \(O(1)\) space.

Edge cases. n = 0 → 1 (loop skipped). x = 0 with negative n would divide by zero (the problem constrains against it). n = -2³¹ is safe because the negation happens on Python ints before any float work.

Multiply Strings

The question. Multiply two non-negative integers given as strings, without built-in big integers.

Input:  num1 = "123", num2 = "456"  ->  "56088"

The idea. Grade-school multiplication into a result array of length m + n. The digit at position i of num1 times the digit at position j of num2 lands at positions i + j and i + j + 1, with carries.

Walk it through. 3 × 6 = 18 writes 8 at the last position, carry 1; then 3 × 5 = 15 plus carry, etc., accumulating column sums.

def multiply(num1, num2):
    if num1 == "0" or num2 == "0":
        return "0"
    m, n = len(num1), len(num2)
    res = [0] * (m + n)
    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            mul = (ord(num1[i]) - 48) * (ord(num2[j]) - 48)
            p1, p2 = i + j, i + j + 1
            total = mul + res[p2]
            res[p2] = total % 10
            res[p1] += total // 10
    out = "".join(map(str, res)).lstrip("0")
    return out or "0"

\(O(mn)\) time, \(O(m + n)\) space.

Detect Squares

The question. Design a structure to add points and count the number of axis-aligned squares with a given query point as the top-left… actually any corner, given three corners.

add([3,10]); add([11,2]); add([3,2]); count([11,10]) -> 1

The idea. Store points in a hash map from (x, y) to count. For a query point, iterate over the points that share its x coordinate (candidate top-left corners); the side length d is the vertical distance; the other two corners must then be (qx + d, qy) and (qx + d, qy + d). Count the product of the multiplicities.

Walk it through on add([3,10]); add([11,2]); add([3,2]); count([11,10]). The only stored point sharing x = 11 with the query is (11,2), with \(d = |2 - 10| = 8\):

Total 1: the square (3,2), (11,2), (3,10), (11,10).

from collections import defaultdict

class DetectSquares:
    def __init__(self):
        self.pts = defaultdict(int)
    def add(self, point):
        self.pts[tuple(point)] += 1
    def count(self, point):
        qx, qy = point
        total = 0
        for (x, y), cnt in self.pts.items():
            if x == qx and abs(y - qy) > 0:            # vertical side to (qx, y)
                d = abs(y - qy)
                total += cnt * self.pts.get((qx + d, y), 0) * self.pts.get((qx + d, qy), 0)
                total += cnt * self.pts.get((qx - d, y), 0) * self.pts.get((qx - d, qy), 0)
        return total

The +d and -d terms cover squares to the right and left of the query point. Counting multiplicities handles duplicate points.

Why anchor on the shared-x point. The query point fixes one corner; the second corner must complete a vertical side, so it shares x with the query. That determines d, and the square’s other two corners are then forced — two dictionary lookups instead of a quadratic search over pairs.

Complexity. \(O(n)\) per count (one scan of stored points), \(O(n)\) space.

Edge cases. Duplicate points multiply the count. d = 0 is excluded (a degenerate point, not a square). No squares → 0.

Pitfalls

QQuestionSelf-check

How does Set Matrix Zeroes use \(O(1)\) space? Why does fast exponentiation run in \(O(\log n)\)?

ASolution

It stores each row’s and column’s “must zero” flag in the matrix’s own first row and column, tracking only whether that first row/column needs zeroing. Fast exponentiation halves the exponent each step and squares the base, so the number of multiplications is the number of bits in n — \(O(\log n)\).

That completes the NeetCode 150, mapped across the series. Pick a pattern, name its invariant, and the problem usually names its own solution.