progress

~/problems / Stacks / Stack: path parsing

Fewest deletions to balance parentheses

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

easy assessment 2 levels ~30 min DoorDash

Level 1 How many to delete

s contains only ( and ). A string is balanced if every ( can be paired with a later ) and nothing is left unpaired. The empty string is balanced.

Write min_deletions(s: str) -> int, the fewest characters you must delete from s so the rest is balanced. s has up to a million characters.

⭐ Bonus: repeatedly deleting "()" pairs still passes; a speed test on a million characters earns a star in O(n) time (O(1) extra space is the classic follow-up).

min_deletions("())(")    # 2
min_deletions("(()")     # 1
min_deletions("()()")    # 0
Show hint

you don't need to remember which characters are unmatched, only how many of each kind.

Level 2 unlocks when level 1 passes.

Topic: Stack: path parsing. Resolve ., .. and symlinks with a stack.

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