progress

~/problems / Arrays & hashing / Hash maps and counting

Longest Common Prefix

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

An autocomplete box fills in the letters every suggestion starts with.

Write shared_beginning(words) -> str that returns the longest string every word in words starts with ("" if none).

shared_beginning(["interval", "internet", "interior"])   # "inter"
shared_beginning(["dog", "cat"])                          # ""
shared_beginning(["solo"])                                # "solo"
shared_beginning(["same", "same"])                        # "same"

Up to 2 * 10^5 lowercase words, 2 * 10^6 letters in total. ⭐ Bonus: speed tests earn a star in O(total length) (testing startswith for every length is quadratic).

Show hint

compare the words column by column; stop at the first mismatch or when a word runs out.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc