Check Bracket Balance in Generated Code Outside String Literals
Last updated: November 29, 2026
Quick Overview
Given source code produced by a model, check that (), [] and {} are balanced and properly nested, ignoring characters inside single or double quoted strings (with backslash escapes); return success or the index of the first problem.
OpenAI
November 29, 20260
0
0 solved
Given source code produced by a model, check that (), [] and {} are balanced and properly nested, ignoring characters inside single or double quoted strings (with backslash escapes); return success or the index of the first problem.
Code generated by OpenAI models is often streamed to users and executed in sandboxes, and cheap structural checks catch truncated or broken output before running it. This screen problem checks stack usage, string-literal handling, and returning a useful error position rather than just true or false.
What the Interviewer Expects
- Use a stack of open bracket positions
- Track whether the scanner is inside a string and which quote opened it
- Skip escaped characters inside strings
- Report the first mismatched closer, or the end of input for unclosed openers
- Test brackets inside strings
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Report the position of the unclosed opener instead of the end of input.
- Support Python triple-quoted strings and comments.
- The code is streaming: how do you validate incrementally and know whether more input could still fix it?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Brackets:
(),[],{}; must match and nest properly. - Text inside
'...'or"..."is ignored; backslash escapes the next character. - Output:
(True, -1)or(False, index): the index of ...
High-Level Design
Scan once with a small state machine. Outside strings, an opener pushes its index, a closer must match the opener on top of the stack, and a quote character enters string mode. Inside a string, a back...