Skip to content

Arrays

Arrays are the most fundamental data structure in programming. They store elements in contiguous memory locations, allowing constant-time access by index.

What is an Array?

An array is a collection of elements stored at contiguous memory locations. Each element can be accessed directly using its index.

Index: 0 1 2 3 4
┌────┬────┬────┬────┬────┐
Array: │ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴────┴────┴────┴────┘

Time Complexity

OperationAverageWorst
AccessO(1)O(1)
SearchO(n)O(n)
Insert (end)O(1)*O(n)
Insert (middle)O(n)O(n)
DeleteO(n)O(n)

*Amortized for dynamic arrays

Basic Operations

Creating and Accessing Arrays

# Creating arrays
arr = [1, 2, 3, 4, 5]
empty = []
sized = [0] * 10 # [0, 0, 0, ..., 0]
# Accessing elements
first = arr[0] # 1
last = arr[-1] # 5
middle = arr[2] # 3
# Slicing
first_three = arr[:3] # [1, 2, 3]
last_two = arr[-2:] # [4, 5]
reversed_arr = arr[::-1] # [5, 4, 3, 2, 1]
# Length
length = len(arr) # 5

Modifying Arrays

arr = [1, 2, 3]
# Adding elements
arr.append(4) # [1, 2, 3, 4]
arr.insert(0, 0) # [0, 1, 2, 3, 4]
arr.extend([5, 6]) # [0, 1, 2, 3, 4, 5, 6]
# Removing elements
arr.pop() # Removes 6, returns 6
arr.pop(0) # Removes 0, returns 0
arr.remove(3) # Removes first occurrence of 3
# Modifying
arr[0] = 10 # Change first element

Common Patterns

1. Two Pointers

Use two pointers moving towards each other or in the same direction.

def two_sum_sorted(arr, target):
"""Find two numbers that sum to target in sorted array"""
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return [-1, -1]

Learn more about Two Pointers →

2. Sliding Window

Maintain a window of elements as you iterate.

def max_sum_subarray(arr, k):
"""Find max sum of subarray of size k"""
if len(arr) < k:
return 0
# Initial window sum
window_sum = sum(arr[:k])
max_sum = window_sum
# Slide the window
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i - k]
max_sum = max(max_sum, window_sum)
return max_sum

Learn more about Sliding Window →

3. Prefix Sum

Precompute cumulative sums for range queries.

def build_prefix_sum(arr):
"""Build prefix sum array"""
prefix = [0] * (len(arr) + 1)
for i in range(len(arr)):
prefix[i + 1] = prefix[i] + arr[i]
return prefix
def range_sum(prefix, left, right):
"""Get sum of elements from left to right (inclusive)"""
return prefix[right + 1] - prefix[left]

Learn more about Prefix Sum →

Practice Problems

Easy

ProblemPatternCompanies
Two SumHash TableAmazon, Google, Meta
Best Time to Buy/Sell StockOne PassAmazon, Meta
Contains DuplicateHash SetAmazon, Apple
Maximum SubarrayKadane’sAmazon, Microsoft

Medium

ProblemPatternCompanies
3SumTwo PointersAmazon, Google, Meta
Container With Most WaterTwo PointersAmazon, Google
Product of Array Except SelfPrefix/SuffixAmazon, Meta
Maximum Product SubarrayDPAmazon, Microsoft

Hard

ProblemPatternCompanies
Trapping Rain WaterTwo Pointers/StackAmazon, Google, Meta
First Missing PositiveIndex MarkingAmazon, Google
Sliding Window MaximumMonotonic DequeAmazon, Google

Key Takeaways

  1. Arrays provide O(1) access - Use index-based access when possible
  2. Insertions/deletions are O(n) - Consider linked lists for frequent modifications
  3. Use built-in methods - They’re optimized and less error-prone
  4. Watch for off-by-one errors - Common source of bugs
  5. Consider space-time tradeoffs - Extra arrays can reduce time complexity

Next Steps