💡 Summary: Numbered Lockers & Flattening a Grid into One Long Strip
A 1D array is like a row of lockers numbered 0, 1, 2, ... right next to each other. Because every locker has the same size $w$ bytes and starts at base address $B$, the computer jumps straight to index $i$ at address $B + i \times w$ in $O(1)$ time without counting from the start.
Physical RAM is one-dimensional, even when you draw a 2D matrix (rows × columns). Row-major order places one full row after another in memory (used by C, C++, Python/NumPy), while column-major order places one full column after another (used by Fortran and MATLAB).
- 1D Array Address (0-based): $\text{Addr}(A[i]) = B + i \cdot w$.
- 2D Row-Major Address (0-based): $\text{Addr}(A[i][j]) = B + (i \cdot C + j) \cdot w$.
- 2D Column-Major Address (0-based): $\text{Addr}(A[i][j]) = B + (j \cdot R + i) \cdot w$.
- 1-based lower bounds ($l_1, l_2$): Substitute $(i - l_1)$ and $(j - l_2)$ into the row/column offsets.
| Layout | How Elements Sit in Memory | 0-Based Address Formula for $A[i][j]$ |
|---|---|---|
| Row-Major | Row 0, then Row 1, then Row 2, ... | $B + (i \times C + j) \times w$ |
| Column-Major | Col 0, then Col 1, then Col 2, ... | $B + (j \times R + i) \times w$ |
# 2D matrix with R = 3 rows, C = 4 columns, base = 1000, element size w = 4 bytes
R, C, BASE, W = 3, 4, 1000, 4
def row_major_addr(i, j):
return BASE + (i * C + j) * W
def col_major_addr(i, j):
return BASE + (j * R + i) * W
# Target element A[1][2] (row 1, col 2)
print("Row-major offset for A[1][2]:", 1 * C + 2, "-> Addr:", row_major_addr(1, 2))
print("Col-major offset for A[1][2]:", 2 * R + 1, "-> Addr:", col_major_addr(1, 2))
- Stride / Flattening Intuition: Each outer index skips a full block of inner elements.
- Cache Locality Matters: Iterating in memory order (row-by-row in row-major layouts) hits adjacent cache lines smoothly instead of jumping across memory pages.
- Cost of Middle Insertions/Deletions: Shifting contiguous elements in a 1D array takes $O(n)$ worst-case time, whereas index lookup takes $O(1)$.
#include
using namespace std;
int main() {
const int ROWS = 2, COLS = 3;
int grid[ROWS][COLS] = {
{10, 20, 30},
{40, 50, 60}
};
cout << "Row-major sequence: ";
for (int r = 0; r < ROWS; ++r) {
for (int c = 0; c < COLS; ++c) {
cout << grid[r][c] << " ";
}
}
cout << "\nElement at [1][2]: " << grid[1][2] << "\n";
return 0;
}
- 1. Digital Grayscale & RGB Image Buffers (2D / 3D Grid): Pixels sit in a 2D height × width grid (plus color channels) for instant pixel reads and filters.
- 2. Cinema & Stadium Seat Maps (2D Row × Seat Grid): Row index and seat index map directly to booking status in $O(1)$ lookup time.
- 3. Spreadsheet / Timetable Grids (2D Rows × Columns): Subjects/days along rows and periods/metrics along columns form a natural 2D table.
- 4. Audio Sample Buffers (1D Time-Series Array): Sound waveforms are stored as sequential amplitude samples indexed by time step.
- 5. Leaderboard / Top-N Scoreboards (1D Ranked Array): Fixed or bounded rank slots allow direct access to rank positions.
# 1. 2D grayscale pixel intensity matrix (3x3)
image = [
[120, 135, 140],
[128, 250, 145],
[110, 125, 130]
]
print("1. Center pixel [1][1]:", image[1][1])
# 2. 2D seat chart (Row 0, Seat 2)
seat_chart = [["free", "booked", "free"], ["free", "free", "booked"]]
print("2. Seat [0][2] status:", seat_chart[0][2])
# 4. 1D audio amplitude samples
samples = [0.0, 0.45, 0.85, 0.30, -0.25]
print("4. Sample at index 2:", samples[2])
# 5. 1D leaderboard scores
scores = [980, 945, 910, 880]
print("5. Rank #2 score:", scores[1])
- 6. Sensor Telemetry Across Multiple Machines & Hours (2D Matrix): Rows represent sensors/machines and columns represent hourly readings for fast slice summaries.
- 7. 2D Board Games Like Chess or Tic-Tac-Toe: Board coordinates
(row, col)track pieces, legal moves, and win checks cleanly. - 8. Scientific / ML Feature & Weight Matrices (Row-Major vs. Column-Major): Matrix math loops benefit when inner loops traverse contiguous elements in memory.
- 9. Warehouse Shelf / Rack Coordinates (2D/3D Grid): Aisle, rack, and shelf numbers act like multi-dimensional indices for item placement.
- 10. Fixed 12-Month Financial or Attendance Summary (1D/2D Array): Months
0..11map directly to monthly totals without searching keys.
# 6. Sensor readings: 2 sensors x 3 hours
sensor_grid = [
[24.5, 25.0, 26.2], # Sensor 0
[60.0, 61.5, 59.0], # Sensor 1
]
print("6. Sensor 0 avg temp:", round(sum(sensor_grid[0]) / len(sensor_grid[0]), 2))
# 7. 3x3 board state
board = [["X", "O", " "], [" ", "X", " "], ["O", " ", "X"]]
print("7. Center cell:", board[1][1])
# 10. 12-month expense array (0-indexed months)
monthly_expenses = [1200, 1150, 1300, 1250, 1400, 1350, 1500, 1450, 1380, 1420, 1550, 1600]
print("10. March (index 2) expense:", monthly_expenses[2])
- Always check indexing base: Confirm whether indices start at
0or a custom lower boundlbefore applying address formulas. - Watch row vs. column count in formulas: Row-major multiplies row index
iby total columnsC; column-major multiplies column indexjby total rowsR. - Know when arrays are ideal vs. costly: Great for fast $O(1)$ indexed access and cache-friendly scans, less ideal when frequent insertions/deletions happen in the middle.
array_tips = [
"Index lookup is O(1) when position is known.",
"Row-major: addr = base + (i * cols + j) * elem_size (0-based).",
"Column-major: addr = base + (j * rows + i) * elem_size (0-based)."
]
for tip in array_tips:
print("-", tip)