Core Module
12 min forge
Array Basics
Master the most fundamental data structure. Learn how arrays work under the hood and common manipulation patterns.
π Array Basics: The Foundation
An array is a collection of items stored at contiguous memory locations. It's the most widely used data structure because of its simplicity and constant-time access.
π‘ The Logic (ELI5)
Think of an array as a row of lockers in a school hallway:
- Every locker has a number (index), starting from 0.
- If you know the locker number, you can walk straight to it and open it.
- If you want to put a new locker in the middle, you have to move all the other lockers to the right to make space.
π The Deep Dive
Core Properties
- Random Access: You can access any element in $O(1)$ time if you know the index.
- Fixed Size (Static): In some languages (C++, Java), arrays have a fixed size. In JavaScript, arrays are dynamic and can grow.
- Contiguous Memory: Elements are placed right next to each other, which makes them very fast for the CPU to read.
Basic Operations (Complexity)
| Operation | Complexity | Description |
|---|---|---|
| Access | O(1) | Reading value at index i |
| Search | O(n) | Linear search for a value |
| Insertion | O(n) | Worse case (inserting at the beginning) |
| Deletion | O(n) | Worse case (deleting from the beginning) |
π οΈ Code Forge: Essential Manipulation
javascript Standard// Initialization const arr = [10, 20, 30, 40, 50]; // 1. Accessing console.log(arr[2]); // 30 (O(1)) // 2. Iterating for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // 3. Common Interview Task: Reverse an Array function reverseArray(arr) { let start = 0; let end = arr.length - 1; while (start < end) { // Swap elements using destructuring [arr[start], arr[end]] = [arr[end], arr[start]]; start++; end--; } return arr; }
π― Interview Pulse
Top "In-Place" Tricks
Interviews often ask you to modify the array without using extra space ($O(1)$ space).
- Two Pointers: Use two pointers (start/end or slow/fast) to swap or compare elements.
- Index-based Hashing: Use the array indexes as keys (if the values are within the range of array size).
Questions to expect
- Find the maximum/minimum element.
- Check if an array is sorted.
- Find the second largest element.
- Move all zeros to the end of the array.