š Array Fundamentals
You're building a game leaderboard. Players can view their rank instantly - that's O(1) access! But adding a new player requires shifting everyone below - that's O(1). Arrays are perfect for some tasks and terrible for others. Let's see when to use them.
What is an Array?
An array is a collection of elements stored in contiguous memory. Think of it like numbered boxes in a row:
Array Structure
Index: 0 1 2 3 4
Value: [10] [20] [30] [40] [50]
ā
Memory address: 1000, 1004, 1008, 1012, 1016...
Key insight: Because elements are next to each other in memory, you can jump directly to any index using math:
address = base_address + (index Ć element_size)
This makes access O(1) - instant, regardless of array size!
Array Operations
Let's see the core operations and their complexities:
Click Run to execute your code
- ā Access by index: O(1) - Lightning fast!
- ā Insert/Delete: O(n) - Must shift elements
- ā Search by value: O(n) - Must check each element
Quick Quiz
-
Why is
array[100]instant (O(1))?Show answer
The computer calculates the exact memory address usingbase + (100 Ć size)and jumps directly there. No loop needed! -
Why is inserting at index 0 slow (O(n))?
Show answer
You must shift ALL existing elements one position to the right to make room. For n elements, that's n shifts = O(n).
See It in Action
Common Array Patterns
Here are techniques you'll use frequently:
Click Run to execute your code
When to Use Arrays
| Use Arrays When | Avoid Arrays When |
|---|---|
| ā You need fast random access | ā Frequent insertions/deletions |
| ā Size is known or fixed | ā Size changes unpredictably |
| ā Iterating through all elements | ā Searching by value frequently |
| ā Memory efficiency matters | ā Need fast insertions at beginning |
Real-World Uses
- Leaderboards: Fast rank lookup
- Image pixels: Direct coordinate access
- Audio samples: Sequential processing
- Database records: Index-based queries
Common Mistakes
ā Index Out of Bounds
arr = [1, 2, 3]
print(arr[3]) # Error! Valid indices: 0, 1, 2
Fix: Always check if index < len(arr)
ā Modifying While Iterating
for i in range(len(arr)):
arr.append(i) # Infinite loop!
Fix: Create a copy or iterate backwards
Summary
The 3-Point Array Guide
- Access: O(1) - Use arrays when you need fast lookups by index
- Insert/Delete: O(n) - Avoid arrays for frequent modifications
- Memory: Contiguous storage = cache-friendly and efficient
Interview tip: When asked "Why use an array?", mention O(1) access and memory locality!
What's Next?
Now that you understand arrays, you're ready for array techniques! Next lesson: Two Pointers - a powerful pattern for solving array problems efficiently.
Enjoying these tutorials?