DSA · Topic 17 of 18 · DP & Advanced Topics

Math & Geometry

Do it on paper with a tiny example first; the code is usually a few careful index moves.

8 problems · Usually O(n²) for an n × n matrix, O(log n) for fast power time, Often O(1) (in place) space

Step 1 Understand it

Remember it by

Do it on paper with a tiny example first; the code is usually a few careful index moves.

Watch it happen

AnimationMath and geometry: carry digits; rotate by transpose + reverse
Read the animation as text
  1. Add one to the number 199, stored as a list of digits. Work from the last digit, just like adding by hand.
  2. Index 2: 9 + 1 = 10. Write 0 and carry 1 to the digit on the left.
  3. Index 1: 9 + 1 = 10. Write 0 and carry 1 to the digit on the left.
  4. Index 0: 1 + 1 = 2. No carry, so stop — the digits further left don't change.
  5. Answer: [2, 0, 0]. Only the trailing 9s change. If every digit is 9 (like 999), all become 0 and a 1 goes in front: [1, 0, 0, 0].

The idea

These problems test careful index handling and small maths facts: rotate a matrix (transpose, then reverse each row), walk in a spiral (shrink four boundaries), add digits with a carry, compute powers by squaring, or detect a repeating number cycle.

Picture it

flowchart LR
  A["1 2 3<br/>4 5 6<br/>7 8 9"] -->|"transpose"| B["1 4 7<br/>2 5 8<br/>3 6 9"] -->|"reverse each row"| C["7 4 1<br/>8 5 2<br/>9 6 3"]
Two simple steps make a 90° clockwise rotation, in place.

Analogy

Turning a photo 90° in an app. Under the hood it's two simple flips: across the diagonal, then left to right.

Where the analogy breaks

The app hides the steps. In an interview you must get every index right, so draw a 3 × 3 example and check each step by hand.

More detail

What it is

Math and Geometry problems are the wildcards of coding interviews. They don't usually require a specific 'Data Structure' like a Tree or a Graph. Instead, they require identifying a mathematical pattern, formula, or geometric property (like grid manipulation) to solve the problem efficiently.

When to use it

  • When rotating matrices or grids 90 degrees.
  • When dealing with purely numerical operations (checking prime numbers, reversing integers, matrix multiplication).
  • When returning purely geometric calculations (points, lines, overlaps).

How it works

This heavily completely depends on the problem! But some common tricks include:\n- **Matrix Rotation**: Transpose the matrix first (swap rows and cols), then reverse each row individually.\n- **Modulo Arithmetic**: Use % 10 to grab the last digit of a number, and / 10 to shave off the last digit.\n- **Greatest Common Divisor**: Used for fraction simplification.

Example walkthrough

Input: Reverse Integer 123

  1. 123 % 10 = 3 (push to result). 123 / 10 = 12.
  2. 12 % 10 = 2 (push 2). 12 / 10 = 1.
  3. 1 % 10 = 1 (push 1). 1 / 10 = 0. Stop.
  4. Result is 321.

Result: 321

Related patterns

  • Bit Manipulation: Math algorithms often dip into binary operations for extreme speed.

Step 2 Recognise it

Words that signal it

  • 'Rotate', 'spiral', 'set zeroes' on a matrix (often 'in place')
  • Digits: 'plus one', 'multiply strings', 'reverse integer'
  • 'Pow(x, n)' → fast power by squaring
  • 'Happy number' → a repeating cycle (use a set or fast/slow)

Don't confuse it with

  • Arrays & Hashing: Happy Number can use a set to spot repeats, or fast and slow pointers like a linked-list cycle.
  • 2-D DP: A grid with rotation or spiral order is index work, not DP: nothing is optimised or counted.

Gut check

Is it really about moving indexes or digits correctly? → small example on paper, then code.

How to recognise it in an interview

The problem is extremely simple to state (e.g. 'Rotate Image', 'Pow(x, n)') but feels impossible to do cleanly without extra space.

Step 3 The template

The general shape. Adapt it to each problem rather than learning one solution per problem.

python
def rotate_clockwise(matrix):
    n = len(matrix)
    for i in range(n):                       # 1. transpose: swap across the diagonal
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:                       # 2. reverse each row
        row.reverse()
The same template in Java
text
class Solution {
    // Reversing an integer safely without string conversion
    public int reverse(int x) {
        long result = 0;
        while (x != 0) {
            int lastDigit = x % 10;
            result = (result * 10) + lastDigit;
            x = x / 10;
        }
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            return 0; // Handle 32-bit overflow
        }
        return (int) result;
    }
}
TimeUsually O(n²) for an n × n matrix, O(log n) for fast power
SpaceOften O(1) (in place)

Common mistakes

  • Rotating the wrong way: transpose + reverse rows is clockwise.
  • Spiral: not re-checking boundaries before the last two directions, so a middle row is printed twice.
  • Forgetting the final carry ([9, 9] + 1 = [1, 0, 0]).
  • Forgetting about 32-bit Integer Overflow! Mathematical operations on huge integers can wrap around and turn negative unexpectedly.
  • Using expensive String conversions (like String.valueOf(number)) when basic % 10 modulo math is infinitely faster.

Step 4 Watch it run

Two problems, traced step by step exactly as the code runs.

Easy example: Plus One

Input: digits = [1, 9, 9]

indexwhat happensdigits
29 + 1 = 10 → write 0, carry 1[1, 9, 0]
19 + 1 = 10 → write 0, carry 1[1, 0, 0]
01 + 1 = 2, no carry → stop[2, 0, 0]

Result: [2, 0, 0]

Notice: Work from the right like column addition. Stop as soon as there's no carry; only all-nines need a new digit in front.

python
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                 # 9 + 1 = 10: write 0, carry 1
    return [1] + digits

Medium example: Rotate Image (90° clockwise, in place)

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

stepmatrix
start[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose (swap across the diagonal)[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
reverse each row[[7, 4, 1], [8, 5, 2], [9, 6, 3]]

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

Notice: The first column read bottom-up (7, 4, 1) becomes the first row — that's what the two steps achieve.

Step 5 Practise

Read each question and say the pattern and the trick out loud before you open the answer. Then solve it on LeetCode. Tick a problem once you've solved it on your own: it comes back for review tomorrow, then after 3, 7, 14 and 30 days, then every month, on the DSA page.

Easy

  1. Happy Number Easy

    Repeatedly replace a number by the sum of the squares of its digits; does it reach 1?

    Show answer

    Technique: Cycle detection (set or fast/slow)

    The clue: Either reaches 1 or loops forever.

    The trick: Track seen numbers in a set (or use fast and slow); a repeat means it never reaches 1.

  2. Plus One Easy

    Add one to a number stored as a list of digits.

    Show answer

    Technique: Carry from the right

    The clue: Digit-by-digit addition.

    The trick: Go right to left: digits under 9 just add one and stop; 9 becomes 0 and carries.

Medium

  1. Rotate Image Medium

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

    Show answer

    Technique: Transpose + reverse rows

    The clue: 'Rotate' a matrix 'in place'.

    The trick: Swap across the diagonal, then reverse every row.

  2. Spiral Matrix Medium

    Return all elements of a matrix in spiral order.

    Show answer

    Technique: Shrinking boundaries

    The clue: 'Spiral order'.

    The trick: Walk the top row, right column, bottom row, left column, shrinking the four boundaries after each; re-check them before the last two sides.

  3. Set Matrix Zeroes Medium

    If a cell is 0, set its whole row and column to 0, in place.

    Show answer

    Technique: First row and column as markers

    The clue: In place, O(1) extra space.

    The trick: Use the first row and column to remember which rows and columns to clear, with one extra flag for the first row (or column) itself.

  4. Pow(x, n) Medium

    Compute x to the power n (n may be negative).

    Show answer

    Technique: Fast power by squaring

    The clue: A big power in O(log n).

    The trick: x^n = (x^(n/2))², times x when n is odd; use 1 / x for negative n.

  5. Multiply Strings Medium

    Multiply two numbers given as strings, without converting them to integers.

    Show answer

    Technique: Grade-school multiplication into a positions array

    The clue: Digits as strings, no big-integer conversion.

    The trick: Digit i × digit j adds to position i + j + 1 of the result; then carry and remove leading zeros.

  6. Detect Squares Medium

    Add points and count axis-aligned squares that use a query point as one corner.

    Show answer

    Technique: Hash map of point counts

    The clue: Count shapes from stored points, quickly.

    The trick: For each stored point diagonal to the query (same distance in x and y), multiply the counts of the two remaining corners.

What to say in the interview

'I need to ensure my mathematical operations check against Integer.MAX_VALUE to prevent nasty overflow bugs.'

Follow-up prep

Review how modulo arithmetic works with negative numbers!