Balanced Brackets Ignoring Escaped String Literals

Difficulty: Hard · Unit 2: Control Flow, Scope & Recursion · Featured in: Tough Challenge

Validate whether brackets `()`, `[]`, `{}` in a snippet of code are balanced. Brackets appearing inside single-quoted `'...'` or double-quoted `"..."` string literals must be ignored. Backslash `\` inside a string escapes the next character (including quotes and `\`). Unclosed string literals are invalid.

Input & Output Format

Input: A single or multi-line snippet read from stdin.

Output: Print `VALID` if all brackets and quotes are balanced, otherwise `INVALID`.

Sample 1

def f(x): return {'msg': "ok (not closed", 'n': [1, 2]}
VALID

The '(' inside "ok (not closed" is inside a string literal and ignored.

Sample 2

print("hello \" [world")
VALID

Escaped quote \" does not close the string; '[' stays inside the string.

Free forever — sign in with email at poorvithmp.com to unlock the dry run, verified Python 3 solution, edge-case traps, and downloads.

Back to Python Notes Hub