Practice problem · easy
A web server routes each address by its start. To group the routes under one handler, the team needs the longest start that every route path shares.
You get the list of route paths, such as /shop/men/shirts. You must return the longest prefix that all of them have in common.
Write common_prefix(paths).
paths are the route paths, made of lowercase letters and /. The same path can appear more than once.Input: paths = ["/shop/men/shirts", "/shop/men/shoes", "/shop/women"]
Output: "/shop/"| Node reached | Next characters in the list | What happens |\n|---|---|---|\n| /shop | / only | go on |\n| /shop/ | m and w | two ways: stop |\n\nAll three paths start with /shop/, and then they split.
Input: paths = ["/a", "/b"]
Output: "/"Both paths start with /, and then a and b differ.
Input: paths = ["/home"]
Output: "/home"With one path, the whole path is the longest shared start.
1 ≤ length of paths ≤ 2000a to z) or /There can be 2,000 paths of 100 characters, so 200,000 characters in all. Reading each character once is fast.
A trie fits well: the shared start is the path from the root where each node has only one way to go.
common_prefix · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.