URL Slug

Medium · rating 1200 · Strings, Implementation

Turn a page title into a URL slug. Read a single line and print it lowercased, with every run of non-alphanumeric characters replaced by a single hyphen, and no leading or trailing hyphen.

For example, Hello, World! Again becomes hello-world-again.

Editorial

Approach

Lowercase the string, then walk it building the result: copy alphanumeric characters straight through, and collapse any run of other characters into a single hyphen. Finally strip hyphens from the two ends so punctuation at the edges doesn't leave a dangling -.

out, prev_hyphen = [], False
for c in input().lower():
    if c.isalnum():
        out.append(c); prev_hyphen = False
    elif not prev_hyphen:
        out.append('-'); prev_hyphen = True
print(''.join(out).strip('-'))

Key detail

The prev_hyphen flag is what collapses runs of separators — without it, two spaces would produce two hyphens.

Complexity

Time: O(n). Space: O(n).

Related problems

Open URL Slug in Code Arena →