Balanced Brackets III
Difficulty: Hard · Topics: Stack, Parsing, Compiler Design
Difficulty: Hard | Tags: Stack, Parsing, Compiler Design
Description
Given a string representing Java source code, check if all braces ({}, (), []) are properly matched and nested. Report any mismatches with their line and column numbers.
Implement:
checkBraces(sourceCode) → { valid: boolean, errors: BraceError[] }
Where BraceError = { line: int, column: int, message: String }
Examples
Example 1 — Balanced:
Input:
"public class Main {\n public static void main(String[] args) {\n System.out.println("Hello");\n }\n }"
Output: { valid: true, errors: [] }
Example 2 — Missing closing brace:
Input:
"public class Main {\n public void foo() {\n if (true) {\n }\n }"
Output:
{ valid: false, errors: [
{line: 3, column: 21, message: "Unmatched opening '{' — expected closing '}'"}
]}
Example 3 — Mismatched:
Input: "int arr[) = {1, 2};"
Output:
{ valid: false, errors: [
{line: 1, column: 9, message: "Mismatched brackets: expected ']' but found ')'"}
]}
Constraints
- Braces inside string literals (
"...") and comments (//,/* */) should be ignored. - Character literals (
'{') should be ignored. - Source code length ≤ 106.
Hints
Hint 1
Use a stack storing the bracket character along with its line and column position.
Hint 2
First, strip or skip string/char literals and comments to avoid false positives.
Hint 3
Track line and column counters: increment column on each character, reset on newlines.