Chapter 19 - Math and Geometry

Careful arithmetic and careful boundaries. No new data structure, but plenty of traps.

Coding Interview Patterns book cover with the Rust logo and a CHAP 19 label, the chapter on math and geometry

This page is the entry point of chapter 19 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

These problems do not share one algorithm. Some are simulations with shrinking boundaries (spiral traversal). Some are about arithmetic limits (reversing a 32-bit integer without overflow). Some replace floating point with exact integers, like representing a slope by a pair reduced with the GCD to count collinear points. Others hide a recurrence, like the Josephus problem.

When to reach for it

  • Matrix traversals with boundaries that move.
  • Results that may not fit in the integer type.
  • Geometry where floating point comparisons would be fragile.

In Rust

  • checked_mul and checked_add return None on overflow instead of wrapping or panicking.
  • The standard library has no gcd: a three-line recursive function does the job.
  • A HashMap<(i32, i32), usize> keyed on the reduced slope counts the points on each line.

Problems in this chapter

  • p406 - Spiral Traversal: Spiral Traversal (Math And Geometry), solved in Rust. Return the elements of a matrix in clockwise spiral order.
  • p411 - Reverse 32-Bit integer: Reverse 32-Bit Integer (Math and Geometry) solved in Rust: reverse the digits of an i32, return 0 on overflow, without 64-bit integers.
  • p415 - Maximum Collinear Points: Maximum Collinear Points (Math And Geometry), solved in Rust. Given a set of 2D points, determine the max number of aligned points. No duplicate points.
  • bonus145 - The Josephus Problem: The Josephus Problem (Math And Geometry), solved in Rust. There are n people standing in a circle, numbered from 0 to n - 1. Starting from person 0, count k…
  • bonus149 - Triangle Numbers: Triangle Numbers (Math And Geometry), solved in Rust. Consider a triangle composed of numbers where the top of the triangle is 1. Each subsequent number in…

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude