Web Analytics

šŸ“Š Array Fundamentals

Beginner ~10 min read

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:

Output
Click Run to execute your code
The Tradeoff:
  • āœ… 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 using base + (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:

Output
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

  1. Access: O(1) - Use arrays when you need fast lookups by index
  2. Insert/Delete: O(n) - Avoid arrays for frequent modifications
  3. 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.

Preview: Two pointers can solve problems like "find two numbers that sum to target" in O(n) instead of O(n²). Stay tuned!