Exercises: Data Structures
Practice lists, dicts, sets, and algorithmic thinking with data structure exercises.
Related chapter: Data Structures Deep Dive
Exercise 1: Remove Duplicates
Write unique(items) that returns a list of unique items preserving order.
unique([1, 2, 2, 3, 1, 4, 3]) # [1, 2, 3, 4]
unique(["a", "b", "a", "c"]) # ["a", "b", "c"]
Exercise 2: Two Sum
Given a list of numbers and a target, return indices of two numbers that add up to the target.
two_sum([2, 7, 11, 15], 9) # [0, 1]
two_sum([3, 2, 4], 6) # [1, 2]
Hint
Use a dict to store {value: index} as you iterate.
Exercise 3: Anagram Checker
Write is_anagram(s1, s2) — case-insensitive, ignore spaces.
is_anagram("listen", "silent") # True
is_anagram("Hello", "Olelh") # True
is_anagram("Python", "Java") # False
Exercise 4: Merge Dictionaries
Write merge_dicts(*dicts) that merges multiple dicts. Later dicts override earlier keys.
merge_dicts({"a": 1}, {"b": 2}, {"a": 3})
# {"a": 3, "b": 2}
Exercise 5: Stack with Min
Implement a Stack class with push, pop, peek, and get_min — all in O(1) time.
s = Stack()
s.push(3)
s.push(1)
s.push(5)
s.get_min() # 1
s.pop()
s.get_min() # 1
Exercise 6: Word Grouping
Group a list of words by their sorted characters (anagram groups):
group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
# [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Challenge: LRU Cache
Implement an LRUCache(capacity) class with get(key) and put(key, value) that evicts the least recently used item when capacity is exceeded.
cache = LRUCache(2)
cache.put(1, "a")
cache.put(2, "b")
cache.get(1) # "a"
cache.put(3, "c") # evicts key 2
cache.get(2) # None
Solution (Exercise 2)
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
complement = target - n
if complement in seen:
return [seen[complement], i]
seen[n] = i
return []
Exercise 7: Rotate List
Write rotate(lst, k) that rotates a list right by k positions.
rotate([1, 2, 3, 4, 5], 2) # [4, 5, 1, 2, 3]
Exercise 8: Frequency Sort
Sort words by frequency (most common first). Break ties alphabetically.
frequency_sort(["i", "love", "python", "i", "love", "coding"])
# ['i', 'love', 'coding', 'python']
Next: Algorithm Exercises