diff --git a/README.md b/README.md
index 4e94bcc..9a61ddf 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,7 @@ One module per article. This repository currently holds:
| [`fresher-qa`](fresher-qa/) | Top 50 Java Interview Questions for Freshers (2026) with Simple Answers | this commit |
| [`stack-queue`](stack-queue/) | Stack and Queue Problems in Java: Balanced Parentheses, Next Greater Element, Min Stack | this commit |
| [`library-management`](library-management/) | Library Management System in Java: Console Version to Spring Boot REST API | this commit |
+| [`matrix`](matrix/) | Matrix Programs in Java: Addition, Multiplication, Transpose, Spiral and Rotation | this commit |
## `collections` module
diff --git a/matrix/README.md b/matrix/README.md
new file mode 100644
index 0000000..2bc9858
--- /dev/null
+++ b/matrix/README.md
@@ -0,0 +1,58 @@
+# matrix
+
+Companion code for the ankurm.com article **Matrix Programs in Java: Addition, Multiplication, Transpose, Spiral and Rotation**.
+
+The five classic lab programs on `int[][]`, each cross-checked with algebraic laws on seeded random
+matrices. Every figure and console line in the article is quoted from a file in `output/`, which the JUnit
+tests write while asserting the same numbers. There is no `docs/` folder: the explanations live in the
+article itself.
+
+## Versions
+
+| Component | Version | Verified against |
+|---|---|---|
+| JDK | Temurin 25.0.5+8 (LTS) | `java -version` |
+| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA) |
+| Maven | 3.9.x | `mvn -version` |
+
+## Quickstart
+
+```bash
+cd matrix
+export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
+./scripts/run-all.sh # runs the tests and regenerates output/*.txt
+```
+
+The first Maven run must be online so the plugins land in the local cache.
+
+## Source layout
+
+```
+matrix/
+├── pom.xml
+├── scripts/run-all.sh
+├── src/main/java/com/ankurm/interviewlab/matrix/
+│ ├── MatrixBasics.java add, subtract, multiply (i-j-k and i-k-j), multiplyExact, identity, copyOf, format
+│ ├── Transpose.java transpose (any shape), transposeInPlace (square), isSymmetric
+│ ├── Spiral.java spiralOrder, spiralMatrix
+│ ├── Rotation.java clockwise, counter-clockwise, 180, in-place (transpose + reverse, layer swaps)
+│ ├── DryRuns.java instrumented copies that record every step
+│ ├── Complexity.java operation counters (counted, not timed)
+│ └── Pitfalls.java six plausible-looking wrong versions
+├── src/test/java/.../ SolutionsTest, DryRunTest, ComplexityTest, RandomAgreementTest, PitfallsTest
+└── output/*.txt captured real output
+```
+
+## Captured output
+
+| File | What it shows |
+|---|---|
+| `01-addition-and-multiplication.txt` | sum, product, shape-mismatch and jagged-row errors |
+| `02-multiply-dry-run.txt` | the four steps that build one cell of a product |
+| `03-transpose.txt` | rectangular transpose, in-place square transpose, symmetric check |
+| `04-spiral-trace.txt`, `04a-spiral-results.txt` | boundary trace of a 3x4 spiral, edge shapes, `spiralMatrix(4)` |
+| `05-rotation.txt` | clockwise, counter-clockwise, 180, both in-place methods, a rectangular rotation |
+| `06-layer-rotation-trace.txt` | each four-cell move of the layer rotation on 3x3 |
+| `07-random-agreement.txt` | nine laws, 2,000 seeded trials each |
+| `08-operation-counts.txt` | multiplications, swaps, moves and visits |
+| `09-pitfalls.txt` | six classic mistakes reproduced |
diff --git a/matrix/output/01-addition-and-multiplication.txt b/matrix/output/01-addition-and-multiplication.txt
new file mode 100644
index 0000000..f156014
--- /dev/null
+++ b/matrix/output/01-addition-and-multiplication.txt
@@ -0,0 +1,30 @@
+Addition and multiplication
+===========================
+
+A + B (both 2x3)
+[1 2 3]
+[4 5 6]
++
+[6 5 4]
+[3 2 1]
+=
+[7 7 7]
+[7 7 7]
+
+X * Y (2x3 times 3x2 gives 2x2)
+[1 2 3]
+[4 5 6]
+*
+[ 7 8]
+[ 9 10]
+[11 12]
+=
+[ 58 64]
+[139 154]
+
+multiply (i-j-k) and multiplyIkj agree: true
+X * I (3x3 identity) equals X: true
+
+add 2x3 + 3x2 -> IllegalArgumentException: cannot add 2x3 and 3x2: both matrices must have the same shape
+multiply 2x3 * 2x3 -> IllegalArgumentException: cannot multiply 2x3 by 2x3: columns of A (3) must equal rows of B (2)
+add with a jagged row -> IllegalArgumentException: row 1 has 1 columns but row 0 has 2
diff --git a/matrix/output/02-multiply-dry-run.txt b/matrix/output/02-multiply-dry-run.txt
new file mode 100644
index 0000000..0cddf73
--- /dev/null
+++ b/matrix/output/02-multiply-dry-run.txt
@@ -0,0 +1,16 @@
+Dry run: one cell of the product
+================================
+
+A (2x3)
+[1 2 3]
+[4 5 6]
+B (3x2)
+[ 7 8]
+[ 9 10]
+[11 12]
+
+cell C[0][1] = row 0 of A dotted with column 1 of B
+k=0: A[0][0] * B[0][1] = 1 * 8 = 8 running total = 8
+k=1: A[0][1] * B[1][1] = 2 * 10 = 20 running total = 28
+k=2: A[0][2] * B[2][1] = 3 * 12 = 36 running total = 64
+C[0][1] = 64
diff --git a/matrix/output/03-transpose.txt b/matrix/output/03-transpose.txt
new file mode 100644
index 0000000..83df931
--- /dev/null
+++ b/matrix/output/03-transpose.txt
@@ -0,0 +1,24 @@
+Transpose
+=========
+
+2x3 matrix
+[1 2 3]
+[4 5 6]
+transpose() gives a 3x2 matrix
+[1 4]
+[2 5]
+[3 6]
+
+3x3 matrix, transposeInPlace()
+[1 2 3]
+[4 5 6]
+[7 8 9]
+becomes
+[1 4 7]
+[2 5 8]
+[3 6 9]
+
+isSymmetric([[1,7,3],[7,4,-5],[3,-5,6]]) = true
+isSymmetric([[1,2],[3,4]]) = false
+
+transposeInPlace on a 2x3 matrix -> IllegalArgumentException: in-place transpose needs a square matrix but got 2x3
diff --git a/matrix/output/04-spiral-trace.txt b/matrix/output/04-spiral-trace.txt
new file mode 100644
index 0000000..d3eca27
--- /dev/null
+++ b/matrix/output/04-spiral-trace.txt
@@ -0,0 +1,19 @@
+Dry run: spiral traversal of a 3x4 matrix
+=========================================
+
+[ 1 2 3 4]
+[ 5 6 7 8]
+[ 9 10 11 12]
+
+round 1: top=0 bottom=2 left=0 right=3
+ top row, left to right -> [1, 2, 3, 4]
+ right column, top to bottom -> [8, 12]
+ bottom row, right to left -> [11, 10, 9]
+ left column, bottom to top -> [5]
+round 2: top=1 bottom=1 left=1 right=2
+ top row, left to right -> [6, 7]
+ right column, top to bottom -> []
+ bottom row skipped (top > bottom)
+ left column, bottom to top -> []
+
+spiralOrder = [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
diff --git a/matrix/output/04a-spiral-results.txt b/matrix/output/04a-spiral-results.txt
new file mode 100644
index 0000000..e5b849d
--- /dev/null
+++ b/matrix/output/04a-spiral-results.txt
@@ -0,0 +1,19 @@
+Spiral traversal results
+========================
+
+3x4 matrix
+[ 1 2 3 4]
+[ 5 6 7 8]
+[ 9 10 11 12]
+spiralOrder = [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
+
+single row [[1,2,3]] -> [1, 2, 3]
+single column [[1],[2],[3]] -> [1, 2, 3]
+single cell [[5]] -> [5]
+
+spiralMatrix(4), the reverse problem
+[ 1 2 3 4]
+[12 13 14 5]
+[11 16 15 6]
+[10 9 8 7]
+spiralOrder(spiralMatrix(4)) = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
diff --git a/matrix/output/05-rotation.txt b/matrix/output/05-rotation.txt
new file mode 100644
index 0000000..becf91c
--- /dev/null
+++ b/matrix/output/05-rotation.txt
@@ -0,0 +1,42 @@
+Rotation
+========
+
+original 3x3
+[1 2 3]
+[4 5 6]
+[7 8 9]
+
+rotateClockwise
+[7 4 1]
+[8 5 2]
+[9 6 3]
+
+rotateCounterClockwise
+[3 6 9]
+[2 5 8]
+[1 4 7]
+
+rotate180
+[9 8 7]
+[6 5 4]
+[3 2 1]
+
+rotateClockwiseInPlace (transpose, then reverse each row)
+[7 4 1]
+[8 5 2]
+[9 6 3]
+
+rotateClockwiseLayers (four-cell moves)
+[7 4 1]
+[8 5 2]
+[9 6 3]
+
+both in-place versions equal rotateClockwise: true
+
+rectangular 2x3 rotated clockwise becomes 3x2 (in-place is impossible: the shape changes)
+[1 2 3]
+[4 5 6]
+->
+[4 1]
+[5 2]
+[6 3]
diff --git a/matrix/output/06-layer-rotation-trace.txt b/matrix/output/06-layer-rotation-trace.txt
new file mode 100644
index 0000000..46bdfae
--- /dev/null
+++ b/matrix/output/06-layer-rotation-trace.txt
@@ -0,0 +1,15 @@
+Dry run: layer-by-layer rotation of a 3x3 matrix
+================================================
+
+[1 2 3]
+[4 5 6]
+[7 8 9]
+
+layer 0, i=0: left 7 -> top, bottom 9 -> left, right 3 -> bottom, top 1 -> right
+ [7 2 1]
+ [4 5 6]
+ [9 8 3]
+layer 0, i=1: left 4 -> top, bottom 8 -> left, right 6 -> bottom, top 2 -> right
+ [7 4 1]
+ [8 5 2]
+ [9 6 3]
diff --git a/matrix/output/07-random-agreement.txt b/matrix/output/07-random-agreement.txt
new file mode 100644
index 0000000..a74364c
--- /dev/null
+++ b/matrix/output/07-random-agreement.txt
@@ -0,0 +1,12 @@
+Seeded random checks (seed 2026, 2000 trials each)
+==================================================
+
+rotateClockwise == transpose-then-reverse == layer swaps (n x n, n = 1..8): 2000 agree, 0 disagree
+four clockwise turns return the original: 2000 agree, 0 disagree
+clockwise then counter-clockwise returns the original: 2000 agree, 0 disagree
+transpose twice returns the original (random m x n): 2000 agree, 0 disagree
+(A * B) transposed == B transposed * A transposed: 2000 agree, 0 disagree
+A * I == A and I * A == A: 2000 agree, 0 disagree
+i-j-k product == i-k-j product: 2000 agree, 0 disagree
+A * (B + C) == A * B + A * C: 2000 agree, 0 disagree
+spiral order is a permutation of all m * n elements: 2000 agree, 0 disagree
diff --git a/matrix/output/08-operation-counts.txt b/matrix/output/08-operation-counts.txt
new file mode 100644
index 0000000..c7f1fe1
--- /dev/null
+++ b/matrix/output/08-operation-counts.txt
@@ -0,0 +1,27 @@
+Operation counts (counted, not timed)
+=====================================
+
+multiplications for an n x n product (i-j-k loop)
+ n = 10 1,000 multiplications
+ n = 100 1,000,000 multiplications
+ n = 200 8,000,000 multiplications
+ doubling n from 100 to 200 multiplies the work by 8
+
+2x3 times 3x2: 12 multiplications (m * n * p = 2 * 3 * 2)
+
+in-place transpose swaps, n x n
+ n = 3 3 swaps (n * (n - 1) / 2 = 3)
+ n = 100 4,950 swaps (n * (n - 1) / 2 = 4,950)
+
+layer rotation four-cell moves, n x n
+ n = 3 2 moves (n * n / 4 rounded down = 2)
+ n = 4 4 moves (n * n / 4 rounded down = 4)
+ n = 100 2,500 moves (n * n / 4 rounded down = 2,500)
+
+spiral: cells visited vs rows * cols
+ 1 x 1 visits = 1 rows * cols = 1
+ 1 x 7 visits = 7 rows * cols = 7
+ 7 x 1 visits = 7 rows * cols = 7
+ 3 x 4 visits = 12 rows * cols = 12
+ 5 x 5 visits = 25 rows * cols = 25
+ 40 x 25 visits = 1,000 rows * cols = 1,000
diff --git a/matrix/output/09-pitfalls.txt b/matrix/output/09-pitfalls.txt
new file mode 100644
index 0000000..472d4c9
--- /dev/null
+++ b/matrix/output/09-pitfalls.txt
@@ -0,0 +1,44 @@
+Six classic mistakes, each reproduced
+=====================================
+
+1. in-place transpose with the inner loop starting at j = 0 instead of j = i + 1
+ input
+ [1 2 3]
+ [4 5 6]
+ [7 8 9]
+ result (identical to the input, every pair was swapped twice)
+ [1 2 3]
+ [4 5 6]
+ [7 8 9]
+
+2. product result allocated as rows(A) x rows(A) instead of rows(A) x cols(B)
+ 2x3 times 3x4, correct result shape 2x4
+ wrong version -> ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
+
+3. spiral without the 'is there still a row / column left?' checks
+ input [[1, 2, 3]] (a single row)
+ wrong = [1, 2, 3, 2, 1]
+ correct = [1, 2, 3]
+
+4. layer rotation with i <= last instead of i < last (the corner is moved twice)
+ input
+ [1 2 3]
+ [4 5 6]
+ [7 8 9]
+ wrong
+ [9 4 7]
+ [8 5 2]
+ [3 6 1]
+ correct
+ [7 4 1]
+ [8 5 2]
+ [9 6 3]
+
+5. 'copy' made with clone() is shallow
+ original = [[1, 2], [3, 4]]; copy = original.clone(); copy[0][0] = 99
+ original[0][0] is now 99 (the rows are shared)
+ copyOf() makes new rows: changing deep[1][1] left original[1][1] at 4
+
+6. int overflow in the dot product
+ [[50000]] * [[50000]] with plain multiply = -1794967296 (true value 2500000000)
+ multiplyExact -> ArithmeticException: integer overflow
diff --git a/matrix/pom.xml b/matrix/pom.xml
new file mode 100644
index 0000000..be3db4c
--- /dev/null
+++ b/matrix/pom.xml
@@ -0,0 +1,64 @@
+
+
+ 4.0.0
+ com.ankurm.interviewlab
+ matrix
+ 1.0.0
+ jar
+
+ java-interview-lab :: matrix
+
+ Runnable companion code for ankurm.com's "Matrix Programs in Java" article: addition, multiplication, transpose,
+ spiral traversal and rotation, with dry runs, operation counts and the classic mistakes.
+
+
+
+ 25
+ UTF-8
+ 6.1.3
+
+
+
+
+
+ org.junit
+ junit-bom
+ ${junit.version}
+ pom
+ import
+
+
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.14.0
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.6.0
+
+ -Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8
+
+
+
+
+
diff --git a/matrix/scripts/run-all.sh b/matrix/scripts/run-all.sh
new file mode 100755
index 0000000..38df9a6
--- /dev/null
+++ b/matrix/scripts/run-all.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
+# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
+# in the article are assertions: they fail the build the moment they stop being true.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+mkdir -p output
+mvn -B -q -T1 test
+echo "done:"; ls -1 output
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/Complexity.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Complexity.java
new file mode 100644
index 0000000..2ed4045
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Complexity.java
@@ -0,0 +1,63 @@
+package com.ankurm.interviewlab.matrix;
+
+/** Operation counters: the algorithms' loops with a counter added. Counted, never timed. */
+public final class Complexity {
+ private Complexity() {}
+
+ /** Number of scalar multiplications performed by the i-j-k product of an (m x n) and an (n x p) matrix. */
+ public static long multiplications(int m, int n, int p) {
+ long count = 0;
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < p; j++) {
+ for (int k = 0; k < n; k++) {
+ count++;
+ }
+ }
+ }
+ return count;
+ }
+
+ /** Number of element swaps made by the in-place square transpose. Equals n * (n - 1) / 2. */
+ public static long transposeSwaps(int n) {
+ long count = 0;
+ for (int i = 0; i < n; i++) {
+ for (int j = i + 1; j < n; j++) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ /** Number of four-cell moves made by the layer-by-layer rotation. */
+ public static long layerMoves(int n) {
+ long count = 0;
+ for (int layer = 0; layer < n / 2; layer++) {
+ int first = layer, last = n - 1 - layer;
+ for (int i = first; i < last; i++) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ /** Number of cells the spiral visits. Must equal rows * cols: every cell exactly once. */
+ public static long spiralVisits(int rows, int cols) {
+ long count = 0;
+ int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
+ while (top <= bottom && left <= right) {
+ count += right - left + 1;
+ top++;
+ count += Math.max(0, bottom - top + 1);
+ right--;
+ if (top <= bottom) {
+ count += Math.max(0, right - left + 1);
+ bottom--;
+ }
+ if (left <= right) {
+ count += Math.max(0, bottom - top + 1);
+ left++;
+ }
+ }
+ return count;
+ }
+}
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/DryRuns.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/DryRuns.java
new file mode 100644
index 0000000..50e8c4b
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/DryRuns.java
@@ -0,0 +1,83 @@
+package com.ankurm.interviewlab.matrix;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Instrumented copies of the real algorithms that record every step, so a dry run is output, not prose. */
+public final class DryRuns {
+ private DryRuns() {}
+
+ /** Every multiply-and-add that builds one cell of the product. */
+ public static List multiplyCell(int[][] a, int[][] b, int i, int j) {
+ List steps = new ArrayList<>();
+ int dot = 0;
+ for (int k = 0; k < a[0].length; k++) {
+ int term = a[i][k] * b[k][j];
+ dot += term;
+ steps.add("k=" + k + ": A[" + i + "][" + k + "] * B[" + k + "][" + j + "] = "
+ + a[i][k] + " * " + b[k][j] + " = " + term + " running total = " + dot);
+ }
+ steps.add("C[" + i + "][" + j + "] = " + dot);
+ return steps;
+ }
+
+ /** The four boundaries and the side being walked, for every pass of the spiral loop. */
+ public static List spiralTrace(int[][] a) {
+ List steps = new ArrayList<>();
+ int top = 0, bottom = a.length - 1, left = 0, right = a[0].length - 1;
+ int round = 1;
+ while (top <= bottom && left <= right) {
+ steps.add("round " + round + ": top=" + top + " bottom=" + bottom + " left=" + left + " right=" + right);
+ List side = new ArrayList<>();
+ for (int j = left; j <= right; j++) side.add(a[top][j]);
+ steps.add(" top row, left to right -> " + side);
+ top++;
+ side = new ArrayList<>();
+ for (int i = top; i <= bottom; i++) side.add(a[i][right]);
+ steps.add(" right column, top to bottom -> " + side);
+ right--;
+ if (top <= bottom) {
+ side = new ArrayList<>();
+ for (int j = right; j >= left; j--) side.add(a[bottom][j]);
+ steps.add(" bottom row, right to left -> " + side);
+ bottom--;
+ } else {
+ steps.add(" bottom row skipped (top > bottom)");
+ }
+ if (left <= right) {
+ side = new ArrayList<>();
+ for (int i = bottom; i >= top; i--) side.add(a[i][left]);
+ steps.add(" left column, bottom to top -> " + side);
+ left++;
+ } else {
+ steps.add(" left column skipped (left > right)");
+ }
+ round++;
+ }
+ return steps;
+ }
+
+ /** Each four-cell move of the layer-by-layer rotation, with the matrix state after it. Mutates {@code a}. */
+ public static List layerTrace(int[][] a) {
+ List steps = new ArrayList<>();
+ int n = a.length;
+ for (int layer = 0; layer < n / 2; layer++) {
+ int first = layer, last = n - 1 - layer;
+ for (int i = first; i < last; i++) {
+ int offset = i - first;
+ int top = a[first][i];
+ int left = a[last - offset][first];
+ int bottom = a[last][last - offset];
+ int right = a[i][last];
+ steps.add("layer " + layer + ", i=" + i + ": left " + left + " -> top, bottom " + bottom
+ + " -> left, right " + right + " -> bottom, top " + top + " -> right");
+ a[first][i] = left;
+ a[last - offset][first] = bottom;
+ a[last][last - offset] = right;
+ a[i][last] = top;
+ steps.add(MatrixBasics.format(a).indent(4).stripTrailing());
+ }
+ }
+ return steps;
+ }
+}
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/MatrixBasics.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/MatrixBasics.java
new file mode 100644
index 0000000..fe29a5f
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/MatrixBasics.java
@@ -0,0 +1,175 @@
+package com.ankurm.interviewlab.matrix;
+
+import java.util.Arrays;
+
+/**
+ * Addition, subtraction and multiplication of rectangular int matrices, plus the small helpers the
+ * other programs share. A matrix here is just an {@code int[][]} whose rows all have the same length.
+ */
+public final class MatrixBasics {
+ private MatrixBasics() {}
+
+ /** Throws if the matrix is empty or jagged (rows of different lengths). */
+ public static void requireRectangular(int[][] m) {
+ if (m.length == 0 || m[0].length == 0) {
+ throw new IllegalArgumentException("matrix must have at least one row and one column");
+ }
+ for (int i = 1; i < m.length; i++) {
+ if (m[i].length != m[0].length) {
+ throw new IllegalArgumentException("row " + i + " has " + m[i].length
+ + " columns but row 0 has " + m[0].length);
+ }
+ }
+ }
+
+ /** Matrix addition. Both matrices must have the same shape. O(rows * cols). */
+ public static int[][] add(int[][] a, int[][] b) {
+ requireRectangular(a);
+ requireRectangular(b);
+ if (a.length != b.length || a[0].length != b[0].length) {
+ throw new IllegalArgumentException("cannot add " + shape(a) + " and " + shape(b)
+ + ": both matrices must have the same shape");
+ }
+ int[][] sum = new int[a.length][a[0].length];
+ for (int i = 0; i < a.length; i++) {
+ for (int j = 0; j < a[0].length; j++) {
+ sum[i][j] = a[i][j] + b[i][j];
+ }
+ }
+ return sum;
+ }
+
+ /** Matrix subtraction. Same shape rule as {@link #add}. */
+ public static int[][] subtract(int[][] a, int[][] b) {
+ requireRectangular(a);
+ requireRectangular(b);
+ if (a.length != b.length || a[0].length != b[0].length) {
+ throw new IllegalArgumentException("cannot subtract " + shape(b) + " from " + shape(a));
+ }
+ int[][] diff = new int[a.length][a[0].length];
+ for (int i = 0; i < a.length; i++) {
+ for (int j = 0; j < a[0].length; j++) {
+ diff[i][j] = a[i][j] - b[i][j];
+ }
+ }
+ return diff;
+ }
+
+ /**
+ * Matrix multiplication, the textbook i-j-k loop. An (m x n) matrix times an (n x p) matrix gives an
+ * (m x p) matrix. O(m * n * p) time, which is O(n^3) for square matrices.
+ */
+ public static int[][] multiply(int[][] a, int[][] b) {
+ requireRectangular(a);
+ requireRectangular(b);
+ int m = a.length, n = a[0].length, p = b[0].length;
+ if (n != b.length) {
+ throw new IllegalArgumentException("cannot multiply " + shape(a) + " by " + shape(b)
+ + ": columns of A (" + n + ") must equal rows of B (" + b.length + ")");
+ }
+ int[][] c = new int[m][p]; // the result shape is rows(A) x cols(B)
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < p; j++) {
+ int dot = 0;
+ for (int k = 0; k < n; k++) {
+ dot += a[i][k] * b[k][j]; // row i of A dotted with column j of B
+ }
+ c[i][j] = dot;
+ }
+ }
+ return c;
+ }
+
+ /**
+ * Same answer as {@link #multiply}, with the two inner loops swapped to i-k-j. It walks both B and C
+ * row by row, which is friendlier to the CPU cache on big matrices. The operation count is identical.
+ */
+ public static int[][] multiplyIkj(int[][] a, int[][] b) {
+ requireRectangular(a);
+ requireRectangular(b);
+ int m = a.length, n = a[0].length, p = b[0].length;
+ if (n != b.length) {
+ throw new IllegalArgumentException("cannot multiply " + shape(a) + " by " + shape(b));
+ }
+ int[][] c = new int[m][p];
+ for (int i = 0; i < m; i++) {
+ for (int k = 0; k < n; k++) {
+ int aik = a[i][k];
+ for (int j = 0; j < p; j++) {
+ c[i][j] += aik * b[k][j];
+ }
+ }
+ }
+ return c;
+ }
+
+ /** Like {@link #multiply} but throws {@link ArithmeticException} instead of silently wrapping around. */
+ public static int[][] multiplyExact(int[][] a, int[][] b) {
+ requireRectangular(a);
+ requireRectangular(b);
+ int m = a.length, n = a[0].length, p = b[0].length;
+ if (n != b.length) {
+ throw new IllegalArgumentException("cannot multiply " + shape(a) + " by " + shape(b));
+ }
+ int[][] c = new int[m][p];
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < p; j++) {
+ int dot = 0;
+ for (int k = 0; k < n; k++) {
+ dot = Math.addExact(dot, Math.multiplyExact(a[i][k], b[k][j]));
+ }
+ c[i][j] = dot;
+ }
+ }
+ return c;
+ }
+
+ /** The n x n identity matrix: 1 on the main diagonal, 0 elsewhere. */
+ public static int[][] identity(int n) {
+ int[][] id = new int[n][n];
+ for (int i = 0; i < n; i++) {
+ id[i][i] = 1;
+ }
+ return id;
+ }
+
+ /** A deep copy. {@code a.clone()} alone is a shallow copy and shares every row with the original. */
+ public static int[][] copyOf(int[][] a) {
+ int[][] copy = new int[a.length][];
+ for (int i = 0; i < a.length; i++) {
+ copy[i] = a[i].clone();
+ }
+ return copy;
+ }
+
+ public static String shape(int[][] m) {
+ return m.length + "x" + (m.length == 0 ? 0 : m[0].length);
+ }
+
+ /** Fixed-width rendering, one row per line, so printed matrices line up in columns. */
+ public static String format(int[][] m) {
+ int width = 1;
+ for (int[] row : m) {
+ for (int v : row) {
+ width = Math.max(width, String.valueOf(v).length());
+ }
+ }
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < m.length; i++) {
+ StringBuilder line = new StringBuilder("[");
+ for (int j = 0; j < m[i].length; j++) {
+ line.append(j == 0 ? "" : " ").append(String.format("%" + width + "d", m[i][j]));
+ }
+ sb.append(line).append("]");
+ if (i < m.length - 1) {
+ sb.append('\n');
+ }
+ }
+ return sb.toString();
+ }
+
+ /** Value equality for two matrices. */
+ public static boolean same(int[][] a, int[][] b) {
+ return Arrays.deepEquals(a, b);
+ }
+}
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/Pitfalls.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Pitfalls.java
new file mode 100644
index 0000000..7fae72b
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Pitfalls.java
@@ -0,0 +1,77 @@
+package com.ankurm.interviewlab.matrix;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Plausible-looking wrong versions, kept so the article can show each one failing. Never use these. */
+public final class Pitfalls {
+ private Pitfalls() {}
+
+ /** WRONG: j starts at 0, so every pair is swapped twice and the matrix ends up unchanged. */
+ public static void transposeInPlaceJFromZero(int[][] a) {
+ int n = a.length;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < n; j++) {
+ int tmp = a[i][j];
+ a[i][j] = a[j][i];
+ a[j][i] = tmp;
+ }
+ }
+ }
+
+ /** WRONG: result sized rows(A) x rows(A), which is only right when B is square-compatible. */
+ public static int[][] multiplyResultWrongShape(int[][] a, int[][] b) {
+ int[][] c = new int[a.length][a.length]; // should be new int[a.length][b[0].length]
+ for (int i = 0; i < a.length; i++) {
+ for (int j = 0; j < b[0].length; j++) {
+ for (int k = 0; k < b.length; k++) {
+ c[i][j] += a[i][k] * b[k][j];
+ }
+ }
+ }
+ return c;
+ }
+
+ /** WRONG: the two "is there still a row / column left?" checks are missing. */
+ public static List spiralNoBoundaryChecks(int[][] a) {
+ List out = new ArrayList<>();
+ int top = 0, bottom = a.length - 1, left = 0, right = a[0].length - 1;
+ while (top <= bottom && left <= right) {
+ for (int j = left; j <= right; j++) out.add(a[top][j]);
+ top++;
+ for (int i = top; i <= bottom; i++) out.add(a[i][right]);
+ right--;
+ for (int j = right; j >= left; j--) out.add(a[bottom][j]);
+ bottom--;
+ for (int i = bottom; i >= top; i--) out.add(a[i][left]);
+ left++;
+ }
+ return out;
+ }
+
+ /** WRONG: i runs to {@code last} inclusive, so the corner cell is moved twice. */
+ public static void rotateLayersInclusiveBound(int[][] a) {
+ int n = a.length;
+ for (int layer = 0; layer < n / 2; layer++) {
+ int first = layer, last = n - 1 - layer;
+ for (int i = first; i <= last; i++) { // should be i < last
+ int offset = i - first;
+ int top = a[first][i];
+ a[first][i] = a[last - offset][first];
+ a[last - offset][first] = a[last][last - offset];
+ a[last][last - offset] = a[i][last];
+ a[i][last] = top;
+ }
+ }
+ }
+
+ /** WRONG: {@code clone()} is shallow, so the "copy" shares every row array with the original. */
+ public static int[][] shallowCopy(int[][] a) {
+ return a.clone();
+ }
+
+ /** WRONG for large values: plain int arithmetic wraps around silently. Same loop as the real multiply. */
+ public static int[][] multiplyWithSilentOverflow(int[][] a, int[][] b) {
+ return MatrixBasics.multiply(a, b);
+ }
+}
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/Rotation.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Rotation.java
new file mode 100644
index 0000000..bbc5590
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Rotation.java
@@ -0,0 +1,86 @@
+package com.ankurm.interviewlab.matrix;
+
+/**
+ * Rotating a matrix by 90 degrees. Clockwise sends element (i, j) of an (m x n) matrix to
+ * (j, m - 1 - i) of the (n x m) result.
+ */
+public final class Rotation {
+ private Rotation() {}
+
+ /** Clockwise rotation into a new matrix. Works for rectangular input. O(m * n) time and space. */
+ public static int[][] rotateClockwise(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ int rows = a.length, cols = a[0].length;
+ int[][] r = new int[cols][rows];
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < cols; j++) {
+ r[j][rows - 1 - i] = a[i][j];
+ }
+ }
+ return r;
+ }
+
+ /** Counter-clockwise rotation into a new matrix: (i, j) goes to (n - 1 - j, i). */
+ public static int[][] rotateCounterClockwise(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ int rows = a.length, cols = a[0].length;
+ int[][] r = new int[cols][rows];
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < cols; j++) {
+ r[cols - 1 - j][i] = a[i][j];
+ }
+ }
+ return r;
+ }
+
+ /** Half-turn: (i, j) goes to (m - 1 - i, n - 1 - j). */
+ public static int[][] rotate180(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ int rows = a.length, cols = a[0].length;
+ int[][] r = new int[rows][cols];
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < cols; j++) {
+ r[rows - 1 - i][cols - 1 - j] = a[i][j];
+ }
+ }
+ return r;
+ }
+
+ /**
+ * In-place clockwise rotation of a SQUARE matrix, O(1) extra space, in two easy steps:
+ * transpose, then reverse every row.
+ */
+ public static void rotateClockwiseInPlace(int[][] a) {
+ Transpose.transposeInPlace(a);
+ for (int[] row : a) {
+ for (int left = 0, right = row.length - 1; left < right; left++, right--) {
+ int tmp = row[left];
+ row[left] = row[right];
+ row[right] = tmp;
+ }
+ }
+ }
+
+ /**
+ * In-place clockwise rotation of a SQUARE matrix, layer by layer: each step moves four cells one
+ * quarter-turn around the ring. Same result as {@link #rotateClockwiseInPlace}, one pass.
+ */
+ public static void rotateClockwiseLayers(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ if (a.length != a[0].length) {
+ throw new IllegalArgumentException("in-place rotation needs a square matrix but got " + MatrixBasics.shape(a));
+ }
+ int n = a.length;
+ for (int layer = 0; layer < n / 2; layer++) {
+ int first = layer, last = n - 1 - layer;
+ for (int i = first; i < last; i++) { // i < last: the corner at 'last' belongs to the next side
+ int offset = i - first;
+ int top = a[first][i];
+ a[first][i] = a[last - offset][first]; // left -> top
+ a[last - offset][first] = a[last][last - offset]; // bottom -> left
+ a[last][last - offset] = a[i][last]; // right -> bottom
+ a[i][last] = top; // top -> right
+ }
+ }
+ }
+}
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/Spiral.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Spiral.java
new file mode 100644
index 0000000..6646557
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Spiral.java
@@ -0,0 +1,71 @@
+package com.ankurm.interviewlab.matrix;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Spiral traversal: walk the outer ring clockwise, shrink the four boundaries, repeat. */
+public final class Spiral {
+ private Spiral() {}
+
+ /** Elements in clockwise spiral order, starting at the top-left corner. O(m * n) time. */
+ public static List spiralOrder(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ List out = new ArrayList<>();
+ int top = 0, bottom = a.length - 1, left = 0, right = a[0].length - 1;
+ while (top <= bottom && left <= right) {
+ for (int j = left; j <= right; j++) { // left to right along the top row
+ out.add(a[top][j]);
+ }
+ top++;
+ for (int i = top; i <= bottom; i++) { // top to bottom down the right column
+ out.add(a[i][right]);
+ }
+ right--;
+ if (top <= bottom) { // a row may be left over ...
+ for (int j = right; j >= left; j--) { // right to left along the bottom row
+ out.add(a[bottom][j]);
+ }
+ bottom--;
+ }
+ if (left <= right) { // ... and so may a column
+ for (int i = bottom; i >= top; i--) { // bottom to top up the left column
+ out.add(a[i][left]);
+ }
+ left++;
+ }
+ }
+ return out;
+ }
+
+ /** The reverse problem: an n x n matrix filled with 1..n*n in clockwise spiral order. */
+ public static int[][] spiralMatrix(int n) {
+ if (n <= 0) {
+ throw new IllegalArgumentException("n must be positive but was " + n);
+ }
+ int[][] m = new int[n][n];
+ int top = 0, bottom = n - 1, left = 0, right = n - 1, next = 1;
+ while (top <= bottom && left <= right) {
+ for (int j = left; j <= right; j++) {
+ m[top][j] = next++;
+ }
+ top++;
+ for (int i = top; i <= bottom; i++) {
+ m[i][right] = next++;
+ }
+ right--;
+ if (top <= bottom) {
+ for (int j = right; j >= left; j--) {
+ m[bottom][j] = next++;
+ }
+ bottom--;
+ }
+ if (left <= right) {
+ for (int i = bottom; i >= top; i--) {
+ m[i][left] = next++;
+ }
+ left++;
+ }
+ }
+ return m;
+ }
+}
diff --git a/matrix/src/main/java/com/ankurm/interviewlab/matrix/Transpose.java b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Transpose.java
new file mode 100644
index 0000000..013187c
--- /dev/null
+++ b/matrix/src/main/java/com/ankurm/interviewlab/matrix/Transpose.java
@@ -0,0 +1,54 @@
+package com.ankurm.interviewlab.matrix;
+
+/** Transpose: row i becomes column i, so element (i, j) moves to (j, i). */
+public final class Transpose {
+ private Transpose() {}
+
+ /** Works for any rectangular matrix: an (m x n) input gives an (n x m) output. O(m * n) time and space. */
+ public static int[][] transpose(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ int rows = a.length, cols = a[0].length;
+ int[][] t = new int[cols][rows];
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < cols; j++) {
+ t[j][i] = a[i][j];
+ }
+ }
+ return t;
+ }
+
+ /**
+ * Transposes a SQUARE matrix inside the same array, O(1) extra space. Only the cells above the diagonal
+ * are visited (j starts at i + 1); each one is swapped with its mirror below the diagonal exactly once.
+ */
+ public static void transposeInPlace(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ if (a.length != a[0].length) {
+ throw new IllegalArgumentException("in-place transpose needs a square matrix but got " + MatrixBasics.shape(a));
+ }
+ int n = a.length;
+ for (int i = 0; i < n; i++) {
+ for (int j = i + 1; j < n; j++) {
+ int tmp = a[i][j];
+ a[i][j] = a[j][i];
+ a[j][i] = tmp;
+ }
+ }
+ }
+
+ /** A matrix is symmetric when it equals its own transpose. */
+ public static boolean isSymmetric(int[][] a) {
+ MatrixBasics.requireRectangular(a);
+ if (a.length != a[0].length) {
+ return false;
+ }
+ for (int i = 0; i < a.length; i++) {
+ for (int j = i + 1; j < a.length; j++) {
+ if (a[i][j] != a[j][i]) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+}
diff --git a/matrix/src/test/java/com/ankurm/interviewlab/matrix/ComplexityTest.java b/matrix/src/test/java/com/ankurm/interviewlab/matrix/ComplexityTest.java
new file mode 100644
index 0000000..1361ea6
--- /dev/null
+++ b/matrix/src/test/java/com/ankurm/interviewlab/matrix/ComplexityTest.java
@@ -0,0 +1,48 @@
+package com.ankurm.interviewlab.matrix;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.ankurm.interviewlab.matrix.support.Transcript;
+import org.junit.jupiter.api.Test;
+
+/** Operation counts, not timings. Writes output/08. */
+class ComplexityTest {
+
+ @Test
+ void counts() {
+ assertEquals(12, Complexity.multiplications(2, 3, 2));
+ assertEquals(1_000, Complexity.multiplications(10, 10, 10));
+ assertEquals(1_000_000, Complexity.multiplications(100, 100, 100));
+ assertEquals(8_000_000, Complexity.multiplications(200, 200, 200));
+ assertEquals(3, Complexity.transposeSwaps(3));
+ assertEquals(4_950, Complexity.transposeSwaps(100));
+ assertEquals(2, Complexity.layerMoves(3));
+ assertEquals(4, Complexity.layerMoves(4));
+ assertEquals(2_500, Complexity.layerMoves(100));
+
+ Transcript t = Transcript.start("08-operation-counts.txt", "Operation counts (counted, not timed)");
+ t.line("multiplications for an n x n product (i-j-k loop)");
+ for (int n : new int[] {10, 100, 200}) {
+ t.line(String.format(" n = %3d %,12d multiplications", n, Complexity.multiplications(n, n, n)));
+ }
+ t.line(" doubling n from 100 to 200 multiplies the work by "
+ + (Complexity.multiplications(200, 200, 200) / Complexity.multiplications(100, 100, 100))).blank();
+ t.line("2x3 times 3x2: " + Complexity.multiplications(2, 3, 2) + " multiplications (m * n * p = 2 * 3 * 2)").blank();
+ t.line("in-place transpose swaps, n x n");
+ for (int n : new int[] {3, 100}) {
+ t.line(String.format(" n = %3d %,6d swaps (n * (n - 1) / 2 = %,d)", n, Complexity.transposeSwaps(n), n * (n - 1) / 2));
+ }
+ t.blank().line("layer rotation four-cell moves, n x n");
+ for (int n : new int[] {3, 4, 100}) {
+ t.line(String.format(" n = %3d %,6d moves (n * n / 4 rounded down = %,d)", n, Complexity.layerMoves(n), n * n / 4));
+ }
+ t.blank().line("spiral: cells visited vs rows * cols");
+ int[][] shapes = {{1, 1}, {1, 7}, {7, 1}, {3, 4}, {5, 5}, {40, 25}};
+ for (int[] s : shapes) {
+ long visits = Complexity.spiralVisits(s[0], s[1]);
+ assertEquals((long) s[0] * s[1], visits);
+ t.line(String.format(" %2d x %-2d visits = %,5d rows * cols = %,5d", s[0], s[1], visits, s[0] * s[1]));
+ }
+ t.flush();
+ }
+}
diff --git a/matrix/src/test/java/com/ankurm/interviewlab/matrix/DryRunTest.java b/matrix/src/test/java/com/ankurm/interviewlab/matrix/DryRunTest.java
new file mode 100644
index 0000000..33b5a57
--- /dev/null
+++ b/matrix/src/test/java/com/ankurm/interviewlab/matrix/DryRunTest.java
@@ -0,0 +1,55 @@
+package com.ankurm.interviewlab.matrix;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.ankurm.interviewlab.matrix.support.Transcript;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+/** Step-by-step traces of three of the algorithms. Writes output/02, 04 and 06. */
+class DryRunTest {
+
+ @Test
+ void multiplyOneCell() {
+ int[][] a = {{1, 2, 3}, {4, 5, 6}};
+ int[][] b = {{7, 8}, {9, 10}, {11, 12}};
+ List steps = DryRuns.multiplyCell(a, b, 0, 1);
+ assertEquals(4, steps.size());
+ assertEquals("C[0][1] = 64", steps.get(3));
+ assertEquals(MatrixBasics.multiply(a, b)[0][1], 64);
+
+ Transcript t = Transcript.start("02-multiply-dry-run.txt", "Dry run: one cell of the product");
+ t.line("A (2x3)").line(MatrixBasics.format(a)).line("B (3x2)").line(MatrixBasics.format(b)).blank();
+ t.line("cell C[0][1] = row 0 of A dotted with column 1 of B");
+ steps.forEach(t::line);
+ t.flush();
+ }
+
+ @Test
+ void spiralTrace() {
+ int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
+ List steps = DryRuns.spiralTrace(a);
+ Transcript t = Transcript.start("04-spiral-trace.txt", "Dry run: spiral traversal of a 3x4 matrix");
+ t.line(MatrixBasics.format(a)).blank();
+ steps.forEach(t::line);
+ t.blank().line("spiralOrder = " + Spiral.spiralOrder(a));
+ t.flush();
+ assertEquals(2, steps.stream().filter(s -> s.startsWith("round")).count());
+ assertEquals(true, steps.contains(" bottom row skipped (top > bottom)"));
+ }
+
+ @Test
+ void layerTrace() {
+ int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+ int[][] expected = Rotation.rotateClockwise(a);
+ List steps = DryRuns.layerTrace(a);
+ assertArrayEquals(expected, a);
+ assertEquals(2 * Complexity.layerMoves(3), steps.size());
+
+ Transcript t = Transcript.start("06-layer-rotation-trace.txt", "Dry run: layer-by-layer rotation of a 3x3 matrix");
+ t.line(MatrixBasics.format(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})).blank();
+ steps.forEach(t::line);
+ t.flush();
+ }
+}
diff --git a/matrix/src/test/java/com/ankurm/interviewlab/matrix/PitfallsTest.java b/matrix/src/test/java/com/ankurm/interviewlab/matrix/PitfallsTest.java
new file mode 100644
index 0000000..8c55b6e
--- /dev/null
+++ b/matrix/src/test/java/com/ankurm/interviewlab/matrix/PitfallsTest.java
@@ -0,0 +1,79 @@
+package com.ankurm.interviewlab.matrix;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.ankurm.interviewlab.matrix.support.Transcript;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+/** Six classic mistakes, each reproduced next to the correct answer. Writes output/09. */
+class PitfallsTest {
+
+ @Test
+ void pitfalls() {
+ Transcript t = Transcript.start("09-pitfalls.txt", "Six classic mistakes, each reproduced");
+
+ int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+ int[][] jZero = MatrixBasics.copyOf(a);
+ Pitfalls.transposeInPlaceJFromZero(jZero);
+ assertArrayEquals(a, jZero);
+ t.line("1. in-place transpose with the inner loop starting at j = 0 instead of j = i + 1");
+ t.line(" input").line(MatrixBasics.format(a).indent(3).stripTrailing());
+ t.line(" result (identical to the input, every pair was swapped twice)")
+ .line(MatrixBasics.format(jZero).indent(3).stripTrailing()).blank();
+
+ int[][] x = {{1, 2, 3}, {4, 5, 6}};
+ int[][] y = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}};
+ ArrayIndexOutOfBoundsException shape = assertThrows(ArrayIndexOutOfBoundsException.class,
+ () -> Pitfalls.multiplyResultWrongShape(x, y));
+ assertEquals(MatrixBasics.shape(MatrixBasics.multiply(x, y)), "2x4");
+ t.line("2. product result allocated as rows(A) x rows(A) instead of rows(A) x cols(B)");
+ t.line(" 2x3 times 3x4, correct result shape " + MatrixBasics.shape(MatrixBasics.multiply(x, y)));
+ t.line(" wrong version -> ArrayIndexOutOfBoundsException: " + shape.getMessage()).blank();
+
+ int[][] row = {{1, 2, 3}};
+ List noChecks = Pitfalls.spiralNoBoundaryChecks(row);
+ List right = Spiral.spiralOrder(row);
+ assertEquals(List.of(1, 2, 3), right);
+ assertFalse(noChecks.equals(right));
+ assertTrue(noChecks.size() > 3);
+ t.line("3. spiral without the 'is there still a row / column left?' checks");
+ t.line(" input [[1, 2, 3]] (a single row)");
+ t.line(" wrong = " + noChecks);
+ t.line(" correct = " + right).blank();
+
+ int[][] inclusive = MatrixBasics.copyOf(a);
+ Pitfalls.rotateLayersInclusiveBound(inclusive);
+ int[][] expected = Rotation.rotateClockwise(a);
+ assertFalse(MatrixBasics.same(expected, inclusive));
+ t.line("4. layer rotation with i <= last instead of i < last (the corner is moved twice)");
+ t.line(" input").line(MatrixBasics.format(a).indent(3).stripTrailing());
+ t.line(" wrong").line(MatrixBasics.format(inclusive).indent(3).stripTrailing());
+ t.line(" correct").line(MatrixBasics.format(expected).indent(3).stripTrailing()).blank();
+
+ int[][] original = {{1, 2}, {3, 4}};
+ int[][] copy = Pitfalls.shallowCopy(original);
+ copy[0][0] = 99;
+ assertEquals(99, original[0][0]);
+ int[][] deep = MatrixBasics.copyOf(original);
+ deep[1][1] = -1;
+ assertEquals(4, original[1][1]);
+ t.line("5. 'copy' made with clone() is shallow");
+ t.line(" original = [[1, 2], [3, 4]]; copy = original.clone(); copy[0][0] = 99");
+ t.line(" original[0][0] is now " + original[0][0] + " (the rows are shared)");
+ t.line(" copyOf() makes new rows: changing deep[1][1] left original[1][1] at " + original[1][1]).blank();
+
+ int[][] big = {{50_000}};
+ int[][] wrapped = Pitfalls.multiplyWithSilentOverflow(big, big);
+ assertEquals(-1_794_967_296, wrapped[0][0]);
+ ArithmeticException overflow = assertThrows(ArithmeticException.class, () -> MatrixBasics.multiplyExact(big, big));
+ t.line("6. int overflow in the dot product");
+ t.line(" [[50000]] * [[50000]] with plain multiply = " + wrapped[0][0] + " (true value 2500000000)");
+ t.line(" multiplyExact -> ArithmeticException: " + overflow.getMessage());
+ t.flush();
+ }
+}
diff --git a/matrix/src/test/java/com/ankurm/interviewlab/matrix/RandomAgreementTest.java b/matrix/src/test/java/com/ankurm/interviewlab/matrix/RandomAgreementTest.java
new file mode 100644
index 0000000..28838e0
--- /dev/null
+++ b/matrix/src/test/java/com/ankurm/interviewlab/matrix/RandomAgreementTest.java
@@ -0,0 +1,91 @@
+package com.ankurm.interviewlab.matrix;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.ankurm.interviewlab.matrix.support.Transcript;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import org.junit.jupiter.api.Test;
+
+/** Algebraic laws checked on seeded random matrices. Writes output/07. */
+class RandomAgreementTest {
+ private static final int TRIALS = 2_000;
+
+ private static int[][] random(Random r, int rows, int cols) {
+ int[][] m = new int[rows][cols];
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < cols; j++) {
+ m[i][j] = r.nextInt(21) - 10;
+ }
+ }
+ return m;
+ }
+
+ @Test
+ void lawsHold() {
+ Random r = new Random(2026);
+ int rotationAgree = 0, fourTurns = 0, transposeTwice = 0, productTranspose = 0, identity = 0,
+ loopOrders = 0, distributive = 0, spiralPermutation = 0, cwThenCcw = 0;
+ for (int t = 0; t < TRIALS; t++) {
+ int n = 1 + r.nextInt(8);
+ int[][] sq = random(r, n, n);
+ int[][] cw = Rotation.rotateClockwise(sq);
+ int[][] viaT = MatrixBasics.copyOf(sq);
+ Rotation.rotateClockwiseInPlace(viaT);
+ int[][] viaL = MatrixBasics.copyOf(sq);
+ Rotation.rotateClockwiseLayers(viaL);
+ assertArrayEquals(cw, viaT);
+ assertArrayEquals(cw, viaL);
+ rotationAgree++;
+
+ assertArrayEquals(sq, Rotation.rotateClockwise(Rotation.rotateClockwise(Rotation.rotateClockwise(cw))));
+ fourTurns++;
+ assertArrayEquals(sq, Rotation.rotateCounterClockwise(cw));
+ cwThenCcw++;
+
+ int rows = 1 + r.nextInt(7), cols = 1 + r.nextInt(7), p = 1 + r.nextInt(7);
+ int[][] a = random(r, rows, cols);
+ int[][] b = random(r, cols, p);
+ int[][] c = random(r, cols, p);
+ assertArrayEquals(a, Transpose.transpose(Transpose.transpose(a)));
+ transposeTwice++;
+ assertArrayEquals(Transpose.transpose(MatrixBasics.multiply(a, b)),
+ MatrixBasics.multiply(Transpose.transpose(b), Transpose.transpose(a)));
+ productTranspose++;
+ assertArrayEquals(a, MatrixBasics.multiply(a, MatrixBasics.identity(cols)));
+ assertArrayEquals(a, MatrixBasics.multiply(MatrixBasics.identity(rows), a));
+ identity++;
+ assertArrayEquals(MatrixBasics.multiply(a, b), MatrixBasics.multiplyIkj(a, b));
+ loopOrders++;
+ assertArrayEquals(MatrixBasics.multiply(a, MatrixBasics.add(b, c)),
+ MatrixBasics.add(MatrixBasics.multiply(a, b), MatrixBasics.multiply(a, c)));
+ distributive++;
+
+ List flat = new ArrayList<>();
+ for (int[] row : a) {
+ for (int v : row) flat.add(v);
+ }
+ List spiral = new ArrayList<>(Spiral.spiralOrder(a));
+ assertEquals(rows * cols, spiral.size());
+ Collections.sort(flat);
+ Collections.sort(spiral);
+ assertEquals(flat, spiral);
+ spiralPermutation++;
+ }
+
+ Transcript t = Transcript.start("07-random-agreement.txt", "Seeded random checks (seed 2026, " + TRIALS + " trials each)");
+ t.line("rotateClockwise == transpose-then-reverse == layer swaps (n x n, n = 1..8): " + rotationAgree + " agree, 0 disagree");
+ t.line("four clockwise turns return the original: " + fourTurns + " agree, 0 disagree");
+ t.line("clockwise then counter-clockwise returns the original: " + cwThenCcw + " agree, 0 disagree");
+ t.line("transpose twice returns the original (random m x n): " + transposeTwice + " agree, 0 disagree");
+ t.line("(A * B) transposed == B transposed * A transposed: " + productTranspose + " agree, 0 disagree");
+ t.line("A * I == A and I * A == A: " + identity + " agree, 0 disagree");
+ t.line("i-j-k product == i-k-j product: " + loopOrders + " agree, 0 disagree");
+ t.line("A * (B + C) == A * B + A * C: " + distributive + " agree, 0 disagree");
+ t.line("spiral order is a permutation of all m * n elements: " + spiralPermutation + " agree, 0 disagree");
+ t.flush();
+ }
+}
diff --git a/matrix/src/test/java/com/ankurm/interviewlab/matrix/SolutionsTest.java b/matrix/src/test/java/com/ankurm/interviewlab/matrix/SolutionsTest.java
new file mode 100644
index 0000000..b008891
--- /dev/null
+++ b/matrix/src/test/java/com/ankurm/interviewlab/matrix/SolutionsTest.java
@@ -0,0 +1,130 @@
+package com.ankurm.interviewlab.matrix;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.ankurm.interviewlab.matrix.support.Transcript;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+/** The five programs on small, hand-checkable inputs. Writes output/01, 03, 05 and 10. */
+class SolutionsTest {
+
+ @Test
+ void additionAndMultiplication() {
+ int[][] a = {{1, 2, 3}, {4, 5, 6}};
+ int[][] b = {{6, 5, 4}, {3, 2, 1}};
+ int[][] sum = MatrixBasics.add(a, b);
+ assertArrayEquals(new int[][] {{7, 7, 7}, {7, 7, 7}}, sum);
+
+ int[][] x = {{1, 2, 3}, {4, 5, 6}};
+ int[][] y = {{7, 8}, {9, 10}, {11, 12}};
+ int[][] product = MatrixBasics.multiply(x, y);
+ assertArrayEquals(new int[][] {{58, 64}, {139, 154}}, product);
+ assertArrayEquals(product, MatrixBasics.multiplyIkj(x, y));
+ assertArrayEquals(x, MatrixBasics.multiply(x, MatrixBasics.identity(3)));
+
+ IllegalArgumentException addErr = assertThrows(IllegalArgumentException.class, () -> MatrixBasics.add(x, y));
+ IllegalArgumentException mulErr = assertThrows(IllegalArgumentException.class, () -> MatrixBasics.multiply(x, x));
+ IllegalArgumentException jagged = assertThrows(IllegalArgumentException.class,
+ () -> MatrixBasics.add(new int[][] {{1, 2}, {3}}, new int[][] {{1, 2}, {3, 4}}));
+
+ Transcript t = Transcript.start("01-addition-and-multiplication.txt", "Addition and multiplication");
+ t.line("A + B (both 2x3)").line(MatrixBasics.format(a)).line("+").line(MatrixBasics.format(b)).line("=")
+ .line(MatrixBasics.format(sum)).blank();
+ t.line("X * Y (2x3 times 3x2 gives 2x2)").line(MatrixBasics.format(x)).line("*").line(MatrixBasics.format(y))
+ .line("=").line(MatrixBasics.format(product)).blank();
+ t.line("multiply (i-j-k) and multiplyIkj agree: " + MatrixBasics.same(product, MatrixBasics.multiplyIkj(x, y)));
+ t.line("X * I (3x3 identity) equals X: " + MatrixBasics.same(x, MatrixBasics.multiply(x, MatrixBasics.identity(3)))).blank();
+ t.line("add 2x3 + 3x2 -> IllegalArgumentException: " + addErr.getMessage());
+ t.line("multiply 2x3 * 2x3 -> IllegalArgumentException: " + mulErr.getMessage());
+ t.line("add with a jagged row -> IllegalArgumentException: " + jagged.getMessage());
+ t.flush();
+ }
+
+ @Test
+ void transpose() {
+ int[][] rect = {{1, 2, 3}, {4, 5, 6}};
+ int[][] tr = Transpose.transpose(rect);
+ assertArrayEquals(new int[][] {{1, 4}, {2, 5}, {3, 6}}, tr);
+
+ int[][] sq = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+ Transpose.transposeInPlace(sq);
+ assertArrayEquals(new int[][] {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}, sq);
+
+ assertTrue(Transpose.isSymmetric(new int[][] {{1, 7, 3}, {7, 4, -5}, {3, -5, 6}}));
+ assertFalse(Transpose.isSymmetric(new int[][] {{1, 2}, {3, 4}}));
+ IllegalArgumentException err = assertThrows(IllegalArgumentException.class, () -> Transpose.transposeInPlace(rect));
+
+ Transcript t = Transcript.start("03-transpose.txt", "Transpose");
+ t.line("2x3 matrix").line(MatrixBasics.format(rect)).line("transpose() gives a 3x2 matrix")
+ .line(MatrixBasics.format(tr)).blank();
+ t.line("3x3 matrix, transposeInPlace()").line(MatrixBasics.format(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))
+ .line("becomes").line(MatrixBasics.format(sq)).blank();
+ t.line("isSymmetric([[1,7,3],[7,4,-5],[3,-5,6]]) = true");
+ t.line("isSymmetric([[1,2],[3,4]]) = false").blank();
+ t.line("transposeInPlace on a 2x3 matrix -> IllegalArgumentException: " + err.getMessage());
+ t.flush();
+ }
+
+ @Test
+ void spiral() {
+ int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
+ List order = Spiral.spiralOrder(a);
+ assertEquals(List.of(1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7), order);
+ assertEquals(List.of(1, 2, 3), Spiral.spiralOrder(new int[][] {{1, 2, 3}}));
+ assertEquals(List.of(1, 2, 3), Spiral.spiralOrder(new int[][] {{1}, {2}, {3}}));
+ assertEquals(List.of(5), Spiral.spiralOrder(new int[][] {{5}}));
+
+ int[][] filled = Spiral.spiralMatrix(4);
+ assertArrayEquals(new int[][] {{1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8, 7}}, filled);
+ assertEquals(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), Spiral.spiralOrder(filled));
+
+ Transcript t = Transcript.start("04a-spiral-results.txt", "Spiral traversal results");
+ t.line("3x4 matrix").line(MatrixBasics.format(a)).line("spiralOrder = " + order).blank();
+ t.line("single row [[1,2,3]] -> " + Spiral.spiralOrder(new int[][] {{1, 2, 3}}));
+ t.line("single column [[1],[2],[3]] -> " + Spiral.spiralOrder(new int[][] {{1}, {2}, {3}}));
+ t.line("single cell [[5]] -> " + Spiral.spiralOrder(new int[][] {{5}})).blank();
+ t.line("spiralMatrix(4), the reverse problem").line(MatrixBasics.format(filled));
+ t.line("spiralOrder(spiralMatrix(4)) = " + Spiral.spiralOrder(filled));
+ t.flush();
+ }
+
+ @Test
+ void rotation() {
+ int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+ int[][] cw = Rotation.rotateClockwise(a);
+ int[][] ccw = Rotation.rotateCounterClockwise(a);
+ int[][] half = Rotation.rotate180(a);
+ assertArrayEquals(new int[][] {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}, cw);
+ assertArrayEquals(new int[][] {{3, 6, 9}, {2, 5, 8}, {1, 4, 7}}, ccw);
+ assertArrayEquals(new int[][] {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}, half);
+
+ int[][] viaTranspose = MatrixBasics.copyOf(a);
+ Rotation.rotateClockwiseInPlace(viaTranspose);
+ int[][] viaLayers = MatrixBasics.copyOf(a);
+ Rotation.rotateClockwiseLayers(viaLayers);
+ assertArrayEquals(cw, viaTranspose);
+ assertArrayEquals(cw, viaLayers);
+
+ int[][] rect = {{1, 2, 3}, {4, 5, 6}};
+ int[][] rectCw = Rotation.rotateClockwise(rect);
+ assertArrayEquals(new int[][] {{4, 1}, {5, 2}, {6, 3}}, rectCw);
+
+ Transcript t = Transcript.start("05-rotation.txt", "Rotation");
+ t.line("original 3x3").line(MatrixBasics.format(a)).blank();
+ t.line("rotateClockwise").line(MatrixBasics.format(cw)).blank();
+ t.line("rotateCounterClockwise").line(MatrixBasics.format(ccw)).blank();
+ t.line("rotate180").line(MatrixBasics.format(half)).blank();
+ t.line("rotateClockwiseInPlace (transpose, then reverse each row)").line(MatrixBasics.format(viaTranspose)).blank();
+ t.line("rotateClockwiseLayers (four-cell moves)").line(MatrixBasics.format(viaLayers)).blank();
+ t.line("both in-place versions equal rotateClockwise: "
+ + (MatrixBasics.same(cw, viaTranspose) && MatrixBasics.same(cw, viaLayers))).blank();
+ t.line("rectangular 2x3 rotated clockwise becomes 3x2 (in-place is impossible: the shape changes)")
+ .line(MatrixBasics.format(rect)).line("->").line(MatrixBasics.format(rectCw));
+ t.flush();
+ }
+}
diff --git a/matrix/src/test/java/com/ankurm/interviewlab/matrix/support/Transcript.java b/matrix/src/test/java/com/ankurm/interviewlab/matrix/support/Transcript.java
new file mode 100644
index 0000000..573b70d
--- /dev/null
+++ b/matrix/src/test/java/com/ankurm/interviewlab/matrix/support/Transcript.java
@@ -0,0 +1,43 @@
+package com.ankurm.interviewlab.matrix.support;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
+public final class Transcript {
+ private final Path path;
+ private final List lines = new ArrayList<>();
+
+ private Transcript(Path path, String header) {
+ this.path = path;
+ lines.add(header);
+ lines.add("=".repeat(Math.min(header.length(), 100)));
+ lines.add("");
+ }
+
+ public static Transcript start(String fileName, String header) {
+ Path dir = Path.of("output");
+ try {
+ Files.createDirectories(dir);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return new Transcript(dir.resolve(fileName), header);
+ }
+
+ public Transcript line(String text) { lines.add(text); return this; }
+ public Transcript blank() { lines.add(""); return this; }
+
+ public void flush() {
+ try {
+ Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+}