Game of Life
Create an empty list replace to store cells that will change.
For each cell (i, j) in the board:
Count live neighbors using 8 surrounding directions.
Apply Game of Life rules:
– Dead cell with 3 live neighbors → becomes alive (1).
– Live cell with <2 or >3 live neighbors → dies (0).
– Live cell with 2 or 3 neighbors → stays same.
After checking all cells, update the board using replace.
Result → board updated in-place to the next generation.
isValidSudoku
Initialize trackers
Create 3 arrays (rows, cols, boxes) — each has 9 sets.
These sets store seen numbers for each row, column, and 3×3 box.
Scan every cell (i, j) in the board.
If the cell contains ".", skip it (empty cell).
Otherwise, take its value val.
Find which 3×3 box the cell belongs to:box = Math.floor(i / 3) * 3 + Math.floor(j / 3)
Check for duplicates:
If val already exists in the same row, column, or box → return false (invalid Sudoku).
Otherwise, record it:
Add val to that row’s, column’s, and box’s set.
After checking all cells → return true.
(Means no duplicates found — Sudoku board is valid.)
Matrix traverse in spiral order
Initialize boundariesimin, imax → top and bottom row indexesjmin, jmax → left and right column indexes
These shrink inward as we traverse layer by layer.
Loop while there are unvisited layerswhile (imin < imax || jmin < jmax)
Traverse the matrix in 4 directions (spiral):
1️⃣ Left → Right (Top row)
Move j from jmin → jmax
Push elements from the top row.
Then, imin++ (top boundary moves down)
2️⃣ Top → Bottom (Right column)
Move i from imin → imax
Push elements from the right column.
Then, jmax-- (right boundary moves left)
3️⃣ Right → Left (Bottom row)
If still rows remain (imin <= imax),
move j from jmax → jmin.
Push elements from the bottom row.
Then, imax-- (bottom boundary moves up)
4️⃣ Bottom → Top (Left column)
If still columns remain (jmin <= jmax),
move i from imax → imin.
Push elements from the left column.
Then, jmin++ (left boundary moves right)
Repeat until all elements are visited.
Return the output array out.
Rotate Matrix
Transpose the matrix
Swap elements across the main diagonal:matrix[i][j] ↔ matrix[j][i]
Converts rows → columns.
Reverse each row
Reverse elements in every row.
Set 0 in row/col if val 0
If any cell is 0, set its entire row and column to 0 — modify in place.
Find all rows and columns that contain a zero.
Use two hash maps (zeroInRow, zeroInCol) to mark which rows and columns should become zero.
Loop through the matrix:
If matrix[i][j] == 0, mark zeroInRow[i] = 1 and zeroInCol[j] = 1.
Set marked rows and columns to zero.
Loop through the matrix again:
If zeroInRow[i] or zeroInCol[j] is marked → set matrix[i][j] = 0.
Result:
All rows and columns containing at least one zero are filled completely with zeros.


