1. Direction Vector & Turn-on-Collision Simulation
Intuition
Mimic a physical pen drawing spiral lines that turns right whenever an obstacle or boundary is encountered.
Algorithm
- Step 1: Allocate matrix of size n x n filled with 0s.
- Step 2: Define directions: dirs = [[0,1], [1,0], [0,-1], [-1,0]]. Initialize dirIdx = 0, r = 0, c = 0.
- Step 3: Loop num from 1 to n*n, setting matrix[r][c] = num.
- Step 4: Calculate candidate next position (nr, nc) = (r + dirs[dirIdx][0], c + dirs[dirIdx][1]).
- Step 5: If (nr, nc) is out of bounds or matrix[nr][nc] != 0, rotate direction: dirIdx = (dirIdx + 1) % 4.
- Step 6: Update r = r + dirs[dirIdx][0] and c = c + dirs[dirIdx][1].
Direction Vector Simulation Trace
2 of 2 questions left todayAllocate 3x3 matrix initialized to 0
Allocate 3x3 matrix initialized to 0. Position (r=0, c=0), direction dr=0, dc=1 (Right).
#include <iostream>#include <vector> class Solution {public: std::vector<std::vector<int>> generateMatrix(int n) { std::vector<std::vector<int>> matrix(n, std::vector<int>(n, 0)); int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // R, D, L, U int d = 0, r = 0, c = 0; for (int num = 1; num <= n * n; ++num) { matrix[r][c] = num; int nr = r + dirs[d][0]; int nc = c + dirs[d][1]; if (nr < 0 || nr >= n || nc < 0 || nc >= n || matrix[nr][nc] != 0) { d = (d + 1) % 4; // Turn clockwise } r += dirs[d][0]; c += dirs[d][1]; } return matrix; }}; int main() { Solution solver; auto res = solver.generateMatrix(3); for (const auto& row : res) { for (int x : row) std::cout << x << " "; std::cout << ""; } return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Direction Vector & Turn-on-Collision Simulation. - Space complexity:
O(1)— Space complexity for Direction Vector & Turn-on-Collision Simulation.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.