1. Full 2D Pascal Triangle Matrix Construction
Intuition
Generate the entire 2D Pascal Triangle up to rowIndex and return the last row.
Algorithm
- 1. Initialize 2D list triangle.
- 2. For r from 0 to rowIndex: - Create row of size r + 1 with boundaries set to 1. - For c from 1 to r - 1: row[c] = triangle[r-1][c-1] + triangle[r-1][c]. - Append row to triangle.
- 3. Return triangle[rowIndex].
Full 2D Triangle Generation Up to rowIndex = 3
2 of 2 questions left todayPhase 1 — Generate Preceding Row 0 & 1: Brute force builds complete 2D triangle from apex
Phase 1 — Generate Preceding Row 0 & 1: Brute force builds complete 2D triangle from apex. Row 0 = [1], Row 1 = [1, 1]. Both rows stored in 2D array.
#include <iostream>#include <vector> using namespace std; class Solution {public: vector<int> getRow(int rowIndex) { vector<vector<int>> triangle; for (int r = 0; r <= rowIndex; ++r) { vector<int> row(r + 1, 1); for (int c = 1; c < r; ++c) { row[c] = triangle[r - 1][c - 1] + triangle[r - 1][c]; } triangle.push_back(row); } return triangle[rowIndex]; }}; int main() { Solution sol; int rowIndex = 3; vector<int> result = sol.getRow(rowIndex); cout << "Pascal's Triangle Row " << rowIndex << ": ["; for (size_t i = 0; i < result.size(); ++i) { cout << result[i] << (i + 1 < result.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(K^2)— Generates all (K+1)*(K+2)/2 elements across K rows in O(K2) time. - Space complexity:
O(K^2)— Stores all previous rows, consuming O(K2) memory.
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.