Spiral Matrix — Direction Array Simulation [Google, Meta, Amazon]
Return all elements of an m×n matrix in spiral order. Use boundary shrinking or direction array. O(m*n) time O(1) space.
webcoderspeed.com
8 articles
Return all elements of an m×n matrix in spiral order. Use boundary shrinking or direction array. O(m*n) time O(1) space.
Rotate an n×n matrix 90 degrees clockwise in-place. Trick: transpose (swap i,j with j,i) then reverse each row. O(n²) time O(1) space.
Find the kth smallest element in a row-column sorted matrix by binary searching on the value range.
Count (row, col) pairs that are equal by hashing each row tuple and each column tuple.
Find the maximal rectangle in a binary matrix by building histogram heights row by row and applying largest rectangle.
Solve linear recurrences like Fibonacci in O(log n) using matrix exponentiation. Essential for DP optimization on large n.
Search for a target in a matrix where each row and column is sorted. O(m+n) solution using top-right corner elimination — a classic Google interview problem.
Calculate how much water can be trapped in a 3D height matrix. Uses a min-heap BFS starting from the boundary, always processing the lowest border cell to determine water trapped inside.