Start free

A level · 4 exercises

Python techniques

Some problems have a known shape. Two pointers move from both ends of a sorted list. A sliding window keeps a running total as it moves, adding one item and taking one away.

A dictionary of what has been seen turns a search inside a loop into a single lookup.

nums = [2, 7, 11, 15]
target = 9
seen = {}
for i, x in enumerate(nums):
    if target - x in seen:
        print(seen[target - x], i)
    seen[x] = i

Watch for: A loop inside a loop over the same long list is slow: the hidden tests may use big inputs.

Exercises

  1. Two numbers to a targetFind the first pair of positions i < j whose numbers add up to the target: theAdvanced
  2. Best k days in a rowFind the largest total of k numbers next to each other.Advanced
  3. Anagram groupsGroup the words that are anagrams of each other.Advanced
  4. Days between datesHow many days are there from the first date to the second?Advanced
Start with “Two numbers to a target”