1. 2D Character Grid Simulation
Intuition
Create a 2D matrix of size numRows x N. Place characters moving down vertically, then diagonally up-right. Concatenate all non-empty characters row by row.
When to apply: Basic visual grid simulation.
Algorithm
- If
numRows == 1 || numRows >= s.length: returns. - Create 2D grid filled with null characters.
- Simulate filling characters moving down and diagonally up.
- Collect characters row by row.
- Return result string.
2D Character Grid Simulation
2 of 2 questions left todayObservation: In a 2D matrix of 3 rows, fill vertically downward
Observation: In a 2D matrix of 3 rows, fill vertically downward.
Decision: Place 'P' at row 0, 'A' at row 1, 'Y' at row 2 in column 0. Turn diagonally up-right.
Invariant: Downward motion populates rows 0 -> numRows - 1.
#include <iostream>#include <string>#include <vector> class Solution {public: std::string convert(std::string s, int numRows) { if (numRows == 1 || numRows >= (int)s.size()) return s; int n = s.size(); std::vector<std::vector<char>> grid(numRows, std::vector<char>(n, 0)); int r = 0, c = 0, dir = 1; for (char ch : s) { grid[r][c] = ch; if (r == 0) dir = 1; else if (r == numRows - 1) dir = -1; if (dir == 1) { r++; } else { r--; c++; } } std::string res = ""; for (int i = 0; i < numRows; ++i) { for (int j = 0; j <= c; ++j) { if (grid[i][j] != 0) res += grid[i][j]; } } return res; }}; int main() { Solution sol; std::cout << sol.convert("PAYPALISHIRING", 3) << std::endl; // PAHNAPLSIIGYIR return 0;}Time & Space Complexity
- Time complexity:
O(numRows * N)— Grid traversal visits cells across the 2D matrix. - Space complexity:
O(numRows * N)
Why Brute Force Doesn't Scale:
Linear arithmetic index jumping produces the output string in a single allocation.
Strict O(1) auxiliary space.