Why Should You Care About Arrays & Strings?
Arrays & strings are everywhere in programming
They're the foundation of almost every program you'll ever write - from contact lists to playlists to search engines.
Phone Contacts
Your phone stores contacts in an array. Each contact has a position (index), making it super fast to jump to any name.
Spotify Playlist
Your playlist is an array of songs! Shuffle rearranges it. Skip moves to the next index.
Text Messages
Every message is a string. When you search for a word, you're using string searching algorithms.
Netflix Recommendations
Watch history is stored in arrays. String matching finds shows with similar titles.
Shopping Cart
Your online cart is an array of items. Adding, removing, updating quantities are all array operations.
Game Inventory
In video games, inventory is an array with limited slots. That's why "inventory full" messages exist!
The Basics: What is an Array?
Think of an array as a parking lot. Each spot has a number, and you can park any car in any spot.
Key Points:
- Each spot has a number (the index)
- Numbering starts at 0, not 1
- All spots are the same size
- Spots are next to each other (contiguous in memory)
Your First Array in Python
# Creating an array (list in Python) is super easy!
my_cars = ["Toyota", "Honda", "Tesla", "BMW"]
# Getting a car from the parking lot (accessing an element)
first_car = my_cars[0] # Gets "Toyota" (spot 0)
third_car = my_cars[2] # Gets "Tesla" (spot 2)
# Changing what's in a spot (updating an element)
my_cars[1] = "Ferrari" # Honda becomes Ferrari!
# How many cars in total? (getting length)
total_cars = len(my_cars) # Returns 4
# Adding a new car at the end
my_cars.append("Porsche") # Now we have 5 cars!
Common Mistake: Index Out of Bounds
Arrays with 3 elements have indices 0, 1, and 2. Accessing index 3 will crash!
# ✘ WRONG - This will crash!
my_array = [10, 20, 30]
value = my_array[3] # Error! Only indices 0, 1, 2
# ✔ CORRECT - Check the length first
my_array = [10, 20, 30]
if 3 < len(my_array):
value = my_array[3]
else:
print("Index doesn't exist!")
# Or use negative indexing (Python feature!)
last_element = my_array[-1] # Gets 30 (last element)
Try It Yourself
Common Patterns
Pattern 1: Two Pointers
Imagine two people starting at different ends of a hallway and walking toward each other. This is the two-pointer technique!
Example: Is this word a palindrome?
A palindrome reads the same forwards and backwards, like "RACECAR".
Start: pointers at both ends
Compare: R == R. Move both inward.
Continue comparing until pointers meet. All match = palindrome!
def is_palindrome(word):
word = word.lower()
left = 0
right = len(word) - 1
while left < right:
if word[left] != word[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
Pattern 2: Sliding Window
Imagine a camera that can only see 3 items at a time. Slide it across to see different groups!
Window sum: 2+4+1 = 7. Slide right to check 4+1+5 = 10...
def max_sum_of_three(numbers):
if len(numbers) < 3:
return None
# Calculate sum of first window
window_sum = numbers[0] + numbers[1] + numbers[2]
max_sum = window_sum
# Slide the window
for i in range(3, len(numbers)):
window_sum -= numbers[i - 3] # Remove leftmost
window_sum += numbers[i] # Add new rightmost
if window_sum > max_sum:
max_sum = window_sum
return max_sum
prices = [100, 200, 50, 400, 300]
print(max_sum_of_three(prices)) # 750 (50 + 400 + 300)
Practice Problems
Easy Problem 1: Find the Largest Number
Given an array of numbers, find the largest one. Think: how would you find the tallest person in a line?
def find_largest(numbers):
if not numbers:
return None
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
print(find_largest([3, 7, 2, 9, 1])) # 9
Easy Problem 2: Reverse an Array
Flip an array so the last element becomes first. [1, 2, 3] becomes [3, 2, 1].
Use two pointers: one at the start, one at the end. Swap and move inward.
def reverse_array(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
# Or Python shorthand: arr[::-1]
Medium Problem 3: Two Sum
Find two numbers in an array that add up to a target. Example: [2, 7, 11, 15], target=9. Answer: indices [0, 1] because 2+7=9.
Use a dictionary to remember numbers you've seen. For each number, check if (target - number) is already in the dictionary.
def two_sum(numbers, target):
seen = {} # {number: index}
for i, num in enumerate(numbers):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
Advanced: String Pattern Matching
Finding patterns in text efficiently - like Ctrl+F in your browser! Instead of checking every position, smart algorithms skip unnecessary comparisons.
Build a "failure table"
Tells us where to jump when we find a mismatch.
Use the table to skip comparisons
Instead of going back to the start, jump ahead to the next possible match position.
def find_pattern(text, pattern):
if not pattern:
return 0
for i in range(len(text) - len(pattern) + 1):
match = True
for j in range(len(pattern)):
if text[i + j] != pattern[j]:
match = False
break
if match:
return i
return -1
text = "The quick brown fox jumps"
print(find_pattern(text, "brown")) # 10
Quick Reference
| Operation | Code | Time | Notes |
|---|---|---|---|
| Access by index | arr[i] |
O(1) | Instant - like opening a specific page |
| Append to end | arr.append(x) |
O(1) | Amortized constant time |
| Insert at beginning | arr.insert(0, x) |
O(n) | Must shift all elements right |
| Search for element | x in arr |
O(n) | Check each item one by one |
| Sort | arr.sort() |
O(n log n) | Timsort in Python |
When to Use Arrays
Fast access by position, known size, lots of iterations, cache-friendly operations.
When NOT to Use
Lots of insertions at beginning, size changes frequently, need key-value pairs, sparse data.
Common Patterns
Two Pointers (palindromes, pair sum), Sliding Window (subarrays), Fast & Slow (cycles), Merge (sorted arrays).