NeetCode 150, stage 17: Math and Geometry

← Intervals · All 150 problems · Bit Manipulation →

These problems have no special data structure. They train exact index work on a matrix and exact arithmetic on digits. A small error in a boundary or in a carry gives a wrong answer, so each template names its moves in a fixed order.

Problems on this page

#ProblemLevelPatternTemplate
148. Rotate ImageMediumTranspose, then reverse the rowsA: Transpose, then reverse
254. Spiral MatrixMediumFour boundaries that shrinkB: Four boundaries that shrink
373. Set Matrix ZeroesMediumFirst row and column as markersC: Markers in the first row and column
4202. Happy NumberEasyDigit loop with cycle detectionD: Digit loop with a carry
566. Plus OneEasyDigit loop with a carryD: Digit loop with a carry
650. Pow(x, n)MediumFast power by squaringE: Fast power by squaring
743. Multiply StringsMediumGrade-school multiplication with digitsD: Digit loop with a carry
82013. Detect SquaresMediumCount map of pointsF: Count map of points

Templates to memorize

Template A: Transpose, then reverse

Signal

The problem asks you to rotate a square matrix in place, with no second matrix.

// TEMPLATE A: turn a square matrix 90 degrees to the right, in place.
func rotateRight(m [][]int) {
    n := len(m)
    for i := 0; i < n; i++ { // 1. TRANSPOSE: mirror on the main diagonal
        for j := i + 1; j < n; j++ { // j > i, or each pair swaps two times
            m[i][j], m[j][i] = m[j][i], m[i][j]
        }
    }
    for _, row := range m { // 2. REVERSE each row
        for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
            row[l], row[r] = row[r], row[l]
        }
    }
}

The moves are TRANSPOSE, then REVERSE each row. In the transpose, start j at i+1. If j starts at 0, each pair swaps two times and the matrix does not change. For a turn to the left, reverse each column and not each row.

Say it

“A 90 degree turn to the right is a transpose followed by a reverse of each row. Both are in-place swaps, so it’s O(n²) time and O(1) space.”

Template B: Four boundaries that shrink

Signal

The problem asks for the cells of a matrix in spiral order, or layer by layer from the outside.

// TEMPLATE B: four boundaries. Walk one side, then move its boundary in.
func spiral(m [][]int) []int {
    top, bottom := 0, len(m)-1
    left, right := 0, len(m[0])-1
    res := make([]int, 0, len(m)*len(m[0]))
    for top <= bottom && left <= right {
        for c := left; c <= right; c++ { // 1. RIGHT on the top row
            res = append(res, m[top][c])
        }
        top++
        for r := top; r <= bottom; r++ { // 2. DOWN on the right column
            res = append(res, m[r][right])
        }
        right--
        if top <= bottom { // CHECK AGAIN: a row is left
            for c := right; c >= left; c-- { // 3. LEFT on the bottom row
                res = append(res, m[bottom][c])
            }
            bottom--
        }
        if left <= right { // CHECK AGAIN: a column is left
            for r := bottom; r >= top; r-- { // 4. UP on the left column
                res = append(res, m[r][left])
            }
            left++
        }
    }
    return res
}

The moves are RIGHT, DOWN, LEFT, UP, and each one moves its boundary in. Before LEFT and before UP, do the CHECK AGAIN. Without it, a matrix with one row or one column gives the same cells two times.

Say it

“I keep top, bottom, left and right. I walk one side, pull that boundary in, and stop when the boundaries cross. Every cell is read once, so it’s O(m times n).”

Template C: Markers in the first row and column

Signal

You must record a fact for each row and each column, and the problem asks for O(1) extra space.

// TEMPLATE C: the first row and the first column hold the markers.
func zeroRowsAndCols(m [][]int) {
    rows, cols := len(m), len(m[0])
    // 1. SAVE: is a zero in the first row or column?
    rowZero, colZero := false, false
    for c := 0; c < cols; c++ {
        rowZero = rowZero || m[0][c] == 0
    }
    for r := 0; r < rows; r++ {
        colZero = colZero || m[r][0] == 0
    }
    // 2. MARK: a zero marks the start of its row and column
    for r := 1; r < rows; r++ {
        for c := 1; c < cols; c++ {
            if m[r][c] == 0 {
                m[r][0], m[0][c] = 0, 0
            }
        }
    }
    for r := 1; r < rows; r++ { // 3. APPLY the markers to the inner cells
        for c := 1; c < cols; c++ {
            if m[r][0] == 0 || m[0][c] == 0 {
                m[r][c] = 0
            }
        }
    }
    if rowZero { // 4. LAST: the first row, then the first column
        for c := 0; c < cols; c++ {
            m[0][c] = 0
        }
    }
    if colZero {
        for r := 0; r < rows; r++ {
            m[r][0] = 0
        }
    }
}

The moves are SAVE, MARK, APPLY, then LAST. The first row and the first column are the marker memory. Save two flags before you mark, because the markers overwrite those two lines. Set the first row and the first column last.

Say it

“I use the first row and the first column as my marker arrays, plus two flags for those two lines themselves. That brings the extra space from O(m plus n) down to O(1).”

Template D: Digit loop with a carry

Signal

The problem works on the digits of a number. The number is an int, a slice of digits or a string that is too long for an int.

// TEMPLATE D: digit loop. n % 10 reads the last digit, and n / 10 removes
// it.
func digitSum(n int) int {
    sum := 0
    for n > 0 {
        sum += n % 10 // 1. POP: read the last digit
        n /= 10       // 2. DROP: remove it
    }
    return sum
}
 
// With a slice of digits, start at the last digit and move a carry to the
// left.
// addDigit adds a one-digit number k to the number in digits.
func addDigit(digits []int, k int) []int {
    carry := k
    for i := len(digits) - 1; i >= 0 && carry > 0; i-- {
        sum := digits[i] + carry
        digits[i] = sum % 10 // KEEP one digit
        carry = sum / 10     // CARRY the rest to the left
    }
    if carry > 0 { // the number has one more digit now
        digits = append([]int{carry}, digits...)
    }
    return digits
}

The moves are POP and DROP for an int. The moves are KEEP and CARRY for a slice of digits. Go from the last digit to the first, because the carry moves to the left. After the loop, check if a carry is left.

Say it

“Mod 10 gives me the last digit and divide by 10 removes it. With digit arrays I work right to left and push the carry along.”

Template E: Fast power by squaring

Signal

The problem asks for a power with a large exponent. A loop that multiplies n times is too slow.

// TEMPLATE E: fast power. Read the bits of n. Needs n >= 0.
func power(x float64, n int) float64 {
    res := 1.0
    for n > 0 {
        if n&1 == 1 { // 1. USE this power when the lowest bit of n is 1
            res *= x
        }
        x *= x  // 2. SQUARE: x, x², x⁴, x⁸ and so on
        n >>= 1 // 3. HALVE: drop the lowest bit
    }
    return res
}

The moves are USE, SQUARE, then HALVE. The loop reads the bits of n from the lowest bit. It runs about 31 times for a 32-bit exponent and not 2 billion times. For a negative exponent, change x to 1/x first.

Say it

“I square the base and halve the exponent, and I multiply the result in whenever the current bit is set. That’s O(log n) multiplications.”

Template F: Count map of points

Signal

A design problem adds points and then asks how many shapes a query point makes. The same point can come more than one time.

// TEMPLATE F: count map of points. The key is the array [2]int{x, y}.
type pointCounter struct {
    count map[[2]int]int
}
 
func newPointCounter() *pointCounter {
    return &pointCounter{count: make(map[[2]int]int)}
}
 
func (pc *pointCounter) add(x, y int) {
    pc.count[[2]int{x, y}]++ // 1. COUNT: a duplicate is one more point
}
 
// squaresAt counts the axis-aligned squares with a corner at (x, y).
func (pc *pointCounter) squaresAt(x, y int) int {
    total := 0
    // 2. DIAGONAL: each stored point is a candidate
    for p, c := range pc.count {
        dx, dy := p[0]-x, p[1]-y
        if dx == 0 || (dx != dy && dx != -dy) {
            continue // not on a diagonal, or a square with no area
        }
        // 3. LOOK UP the two other corners and MULTIPLY the counts.
        total += c * pc.count[[2]int{x, p[1]}] * pc.count[[2]int{p[0], y}]
    }
    return total
}

The moves are COUNT, DIAGONAL, LOOK UP, then MULTIPLY. Two corners on a diagonal fix the full square, so the loop needs only one stored point. The map gives the counts of the two other corners in O(1).

Say it

“I store a count per point. For a query I try every stored point as the diagonal corner, look up the other two corners, and multiply the three counts.”

Mistakes in this stage

  • row := matrix[i] is not a copy. The row shares its memory with the matrix, so a write to row changes the matrix.
  • A slice cannot be a map key. Use the array [2]int{x, y} for a point.
  • In Go, -7 % 10 is -3 and -7 / 10 is 0. The remainder has the sign of the first number.
  • num[i] of a string is a byte with an ASCII code. Subtract '0' and convert to int before you multiply.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

48. Rotate Image

LeetCode 48 · Medium

54. Spiral Matrix

LeetCode 54 · Medium

73. Set Matrix Zeroes

LeetCode 73 · Medium

202. Happy Number

LeetCode 202 · Easy

66. Plus One

LeetCode 66 · Easy

50. Pow(x, n)

LeetCode 50 · Medium

43. Multiply Strings

LeetCode 43 · Medium

2013. Detect Squares

LeetCode 2013 · Medium


← Intervals · All 150 problems · Bit Manipulation →