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

833. Check brackets and report the first error position

EasyTokenization and NLP

Before parsing a model's structured output, you want a quick check that its brackets are balanced. Only (), [] and {} count; every other character is ignored.

Write first_bracket_error(s). Return -1 if every bracket is matched and correctly nested. Otherwise, if some closing bracket has no matching opener (or closes the wrong type), return the index of the first such closing bracket. If the scan ends with openers still unclosed, return the index of the earliest unclosed opener.

Functiondef first_bracket_error(s)

Example 1

Input: first_bracket_error("f(a[1], {b})")

Output: -1

Example 2

Input: first_bracket_error("([)]")

Output: 2

Explanation: Because ")" tries to close "[".

Constraints

  • len(s) <= 100,000
Hint 1

Map each closer to its opener.

Hint 2

Push indices, not characters.

Hint 3

Leftover openers mean the string ended too early.

Common mistakes
  • Only counting opens and closes, which accepts "([)]".
  • Popping from an empty stack.
  • Returning the last unclosed opener instead of the first.
Understand the idea

Bracket matching is the standard use of a stack: the most recently opened bracket must be closed first. For "{[()]" the stack goes {, {[, {[(, then ) pops (, ] pops [, and { remains, so the error is at index 0. Reporting a position instead of a yes or no answer is what makes the check useful for debugging model outputs.

Topics
Tokenization and NLP
Similar questions
  • Score words by TF-IDFEasy
  • Encode text with a byte fallback so no character is ever unknownEasy
  • Normalize text by lowercasing, stripping accents and collapsing spacesEasy
  • Count word n-grams and return the k most frequent with stable tiesEasy
All Tokenization and NLP problems
Report
833 / 903
Python 3solution.pyPython idle
1
2
3
4
def first_bracket_error(s):
# -1 if balanced, else index of the first error
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 7 tests.

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