Arrays
Part of Data Structures & Algorithms
What is an Array?
An array is a fundamental data structure that stores elements in contiguous memory locations. Think of it like a row of boxes, where each box can hold one item and has a number (index) so you can find it quickly.
Real-world Analogy
Imagine a parking lot where each spot has a number. You can go directly to spot #5 without checking spots 1-4. That is how arrays work - you can jump to any position instantly!
Key Characteristics
Fixed vs Dynamic Size
Traditional arrays have fixed size (C, Java), while dynamic arrays (Python lists, JavaScript arrays) can grow automatically.
Same Data Type
In typed languages, arrays typically hold elements of the same type. Dynamic languages like Python allow mixed types.
Zero-Indexed
Most languages start counting from 0, so the first element is at index 0, the second at index 1, and so on.
Contiguous Memory
Elements are stored next to each other in memory, enabling fast access and efficient iteration.
Interactive Array Visualization
Experiment with array operations below. Insert, delete, and sort elements to see how the array changes.
Time & Space Complexity
| Operation | Time Complexity | Explanation |
|---|---|---|
| Access by Index | O(1) | Direct calculation of memory address |
| Search (unsorted) | O(n) | May need to check every element |
| Insert at End | O(1)* | Amortized for dynamic arrays |
| Insert at Beginning | O(n) | All elements must shift right |
| Delete from End | O(1) | Just decrease the size |
| Delete from Beginning | O(n) | All elements must shift left |
Space Complexity: O(n) where n is the number of elements
Code Examples
# Creating an array (list in Python)
numbers = [10, 20, 30, 40, 50]
# Accessing elements by index
first = numbers[0] # 10
last = numbers[-1] # 50
# Inserting an element
numbers.append(60) # Add to end
numbers.insert(2, 25) # Insert at index 2
# Removing elements
numbers.pop() # Remove last element
numbers.remove(30) # Remove first occurrence of 30
# Iterating through array
for num in numbers:
print(num)Common Mistakes to Avoid
Off-by-One Errors
Remember that arrays are 0-indexed. An array of length 5 has indices 0 to 4, not 1 to 5.
Array Index Out of Bounds
Always check if an index is valid before accessing. Accessing index -1 or length will cause errors in most languages.
Modifying While Iterating
Avoid adding or removing elements while looping through an array. This can skip elements or cause infinite loops.
Interview Patterns
Two Pointer Technique
Use two pointers (start/end or slow/fast) to solve problems like finding pairs, reversing arrays, or detecting cycles.
Sliding Window
Maintain a window of elements for problems involving subarrays - maximum sum subarray, longest substring, etc.
Prefix Sum
Pre-calculate cumulative sums for quick range sum queries. Turns O(n) queries into O(1).
Test Your Knowledge
Arrays Quiz
Question 1 of 4What is the time complexity of accessing an element by index in an array?