Loading...
Loading...
DSA
Mastery
Complete Guide
WoHoTech Edition
A deep, visual, example-driven journey from fundamentals to advanced topics, built for real understanding and not just interviews.
12
Chapters
60+
Topics
200+
Examples
Interactive
Diagrams
Chapter 1 of 12 - In Progress
Table of Contents
Chapter 01 - Topic 1.1 of 5
Chapter 01 - Topic 1.1
An array is the most fundamental data structure in computer science. It stores elements in a contiguous block of memory, so every element lives right next to the previous one. This is why arrays give O(1) index access, but fixed size and resizing become their biggest weakness.
Definition
Contiguous memory = cache-friendly = faster than linked lists in practice.Imagine RAM as a long street of numbered houses. When you declare an array, the system reserves consecutive houses. If an integer is 4 bytes and the base address starts at 1000, the layout looks like this.
Address: 1000 1004 1008 1012 1016
┌────┬──────┬──────┬──────┬──────┐
Value: │ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴──────┴──────┴──────┴──────┘
Index: [0] [1] [2] [3] [4]The O(1) Address Formula
address = base_address + (i × size_of_element) address = 1000 + (3 × 4) = 1012 → element is 40
No loop is needed. One multiplication and one addition are enough, which is why array access is O(1).
// 1D Array
int[] arr = {1, 2, 3, 4, 5};
// 2D Array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// 3D Array
int[][][] cube = new int[3][3][3];2D Address Formula
address = base + (row × numCols + col) × elementSize
| Operation | Complexity | Why? |
|---|---|---|
| Access by index | O(1) | Address formula |
| Search (unsorted) | O(n) | May check every element |
| Search (sorted) | O(log n) | Binary search halves range |
| Insert at end | O(1) | Write at known address |
| Insert at middle | O(n) | Must shift elements right |
| Delete at middle | O(n) | Must shift elements left |
| Space | O(n) | n elements stored |
Linear Search - Step by Step
Step 0: check index 0 → 15 ≠ 42, continue Step 1: check index 1 → 32 ≠ 42, continue Step 2: check index 2 → 42 == 42, FOUND at index 2 ✓
Interactive demo for target 42:
Press "Start Search" to begin checking for 42.
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
// Time: O(n) Space: O(1)Find maximum element
function findMax(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}Reverse an array in-place
function reverse(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr;
}Check if array is sorted
function isSorted(arr) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) return false;
}
return true;
}Arrays & Strings - Topics