Skip to content

Exercises — Lists

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]

▶ Try in Playground

Given a list of strings, return a new list with each string reversed.

words = ["hello", "world", "python"]
# expected: ["olleh", "dlrow", "nohtyp"]

▶ Try in Playground

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"

▶ Try in Playground

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 this

▶ Try in Playground

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]

▶ Try in Playground

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: recursion

▶ Try in Playground

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) - height

▶ Try in Playground

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 run

▶ Try in Playground

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

▶ Try in Playground