← Questions
Minimum add to make parentheses valid
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Jan 2026. It tests strings and greedy.
A string contains only ( and ). Return the fewest parentheses you must insert, anywhere, to make it balanced: every ( has a matching ) after it and pairs nest properly.
Interface
Unless you agree on a different interface with the interviewer, assume:
min_add_to_make_valid(s: str) -> int
Example
min_add_to_make_valid("())") -> 1 # insert "(" at the front: "(())"
min_add_to_make_valid("(((") -> 3
min_add_to_make_valid("()") -> 0
min_add_to_make_valid(")(") -> 2
min_add_to_make_valid("()))((") -> 4
Constraints
-
1 <= len(s) <= 100,000. - Target
O(n)time andO(1)extra space.
Clarifying questions
- Can the string contain other characters, and should they be ignored?
- Do you want only the count, or also one balanced result?
- Is the empty string valid?
What a strong answer covers
- One left-to-right pass with an
opencounter:(increments it;)decrements it if positive, otherwise it is unmatched and counts as one insertion. - The answer is the unmatched
)count plus theopencount left at the end. - Why this is minimal: each unmatched character needs its own partner, and no insertion can fix two.
- Tests: already balanced, only openers, only closers, closers before openers.
Follow-ups
- Return the length of the unmatched part instead, or the balanced string itself.
- Remove the fewest parentheses instead of inserting, and return one valid result.
- Each
)must be matched by))(two closers per opener).
Where it's asked
- Meta · AI-enabled coding · Last asked Jan 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
