BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP34 of 38 in topic

779. Repair LLM-generated SQL and formulas: remove the fewest brackets

MediumTokenization and NLP Pro

An LLM writes SQL filters and math formulas for your analytics product, and sometimes the output has unbalanced parentheses: one too many ')' at the end, or a '(' that was never closed because the response was cut off at the token limit. The parser then rejects the whole query. Before parsing, a repair step removes as few parentheses as possible so every bracket is matched.

Write min_remove_to_valid(s). Remove the fewest '(' and ')' characters so that every ')' closes an earlier '(' and every '(' is closed. Keep every other character (letters, digits, spaces, operators, quotes, commas) exactly in order.

Several answers can be minimal, so use this rule: scan left to right and drop each ')' that has no open '(' to match; then drop the '(' that are still unmatched at the end.

Constraints:
- len(s) can be 100,000 (long generated code), with tens of thousands of bad brackets. Keep the positions to drop in a set, not a list: checking i in drop_list for every character is about 100,000 x 100,000 steps.
- '' returns '', and so does a string whose parentheses all have to go, such as '))(('.

Functiondef min_remove_to_valid(s)

Example 1

Input: min_remove_to_valid('lee(t(c)o)de)')

Output: 'lee(t(c)o)de'

Example 2

Input: min_remove_to_valid('a)b(c)d')

Output: 'ab(c)d'

Example 3

Input: min_remove_to_valid('WHERE (a = 1 AND (b = 2 OR c = 3)')

Output: 'WHERE a = 1 AND (b = 2 OR c = 3)'

Explanation: The response was cut off before the outer bracket closed, so that '(' is dropped.

Constraints

  • Length up to 200,000.
  • Only '(' and ')' count as brackets.
Hint 1

Store indices, not characters.

Hint 2

An unmatched ')' is known the moment you see it.

Hint 3

Unmatched '(' are only known at the end.

Common mistakes
  • Removing characters from the string while scanning, which shifts indices.
  • Dropping the first unmatched '(' instead of the ones left on the stack, which breaks the tie rule.
  • Using string concatenation in a loop on very long inputs.
Understand the idea

Bracket matching is the classic stack problem. Track how many opens are waiting; a close either matches the most recent open or is unmatched. Counting alone tells you how many to delete, while storing indices on a stack tells you which ones. The same pattern appears when you repair truncated JSON from a streaming model or check balanced tags in markup.

Topics
Tokenization and NLP
Similar questions
  • Do one merge step of a BPE tokenizerMedium
  • Compute Levenshtein edit distanceMedium
  • Tokenize words with WordPiece greedy longest matchMedium
  • Build a vocabulary with special tokens, a minimum frequency and UNKMedium
All Tokenization and NLP problems
Report
779 / 903
Python 3solution.pyPython idle
1
2
3
4
def min_remove_to_valid(s):
# return s with the fewest parentheses removed
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS