Match opening and closing tags
Python data engineering interview problem. Difficulty: intermediate. Pattern: Strings. About 15 minutes. Part of the Pro drill bank.
A templating engine emits opening and closing tags. A linter should reject a fragment where tags nest incorrectly, the same way brackets must balance in code.
A small template engine uses tags like <a> and </a>. Before rendering, it must check that every opening tag has a matching closing tag, in the right order. Return True if all tags are properly nested and closed, otherwise False. Tags are lowercase letters in angle brackets. Any other text is ignored. Write tags_balanced(s). '<a><b></b></a>' is balanced. '<a></b>' is not, because </b> closes something that was never opened. The starter file already has the function name and its print lines. Keep them and fill in the body.
Requirements
- Every opening tag needs a closing tag with the same name.
- Tags must be closed in the reverse order they were opened.
- Return False for a stray closing tag or a tag left open.
- Return True when all tags match.
Constraints
- Tag names are lowercase letters.
- Text outside tags is ignored.
Examples
Input: tags_balanced('<a><b></b></a>') Output: True This input follows the stated rules and produces this output.
Topics: lakebench, python, stack.
More Python interview questions · All interview problems · Learn data engineering
Match opening and closing tags
Interview-style drill: Validate whether a simplified markup string has properly nested and matched tags.
Return whether opening and closing tags are correctly matched and nested.