Exercises — Lists
Exercise 4.2.1 Beginner
Section titled “Exercise 4.2.1 Beginner”Given a list of integers, return a new list containing only the even numbers, in the same order.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# expected: [2, 4, 6, 8, 10]Exercise 4.2.2 Beginner
Section titled “Exercise 4.2.2 Beginner”Given a list of strings, return a new list with each string reversed.
words = ["hello", "world", "python"]# expected: ["olleh", "dlrow", "nohtyp"]Exercise 4.2.3 Intermediate
Section titled “Exercise 4.2.3 Intermediate”Given a list that may contain duplicates, return a new list with duplicates removed but preserving the original order.
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]# expected: [3, 1, 4, 5, 9, 2, 6]# hint: a set loses order — think about what else tracks "seen"Exercise 4.2.4 Intermediate
Section titled “Exercise 4.2.4 Intermediate”Given two lists of equal length, return a list of tuples pairing each element by position.
names = ["Alice", "Bob", "Carol"]scores = [95, 87, 92]# expected: [("Alice", 95), ("Bob", 87), ("Carol", 92)]# hint: there's a built-in for thisExercise 4.2.5 Intermediate
Section titled “Exercise 4.2.5 Intermediate”Given a list of integers, rotate it to the right by k positions (elements that fall off the end wrap to the front).
nums = [1, 2, 3, 4, 5]k = 2# expected: [4, 5, 1, 2, 3]Exercise 4.2.6 Advanced
Section titled “Exercise 4.2.6 Advanced”Given a nested list of arbitrary depth, return a flat list containing all values.
nested = [1, [2, [3, 4], 5], [6, 7]]# expected: [1, 2, 3, 4, 5, 6, 7]# hint: recursionExercise 4.2.7 Advanced
Section titled “Exercise 4.2.7 Advanced”Given a list of non-negative integers where each value is the height of a bar of width 1, return how much rain water is trapped between the bars after it rains.
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]# expected: 6# hint: two pointers; each bar holds min(left_max, right_max) - heightExercise 4.2.8 Advanced
Section titled “Exercise 4.2.8 Advanced”Given an unsorted list of integers, return the length of the longest run of consecutive integers. The run does not need to be contiguous in the list. Aim for O(n) time.
nums = [100, 4, 200, 1, 3, 2]# expected: 4 (the run 1, 2, 3, 4)# hint: put them in a set, and only start counting from the start of a runExercise 4.2.9 Advanced
Section titled “Exercise 4.2.9 Advanced”Given a list of integers and a window size k, return the maximum of each contiguous window of size k as it slides from left to right.
nums = [1, 3, -1, -3, 5, 3, 6, 7]k = 3# expected: [3, 3, 5, 5, 6, 7]# hint: a deque of indices kept in decreasing value order