Check Block Nesting in a Flat Marker Sequence
Stacks & QueuesAuto-graded · 23 test casesLast updated
Scan a list of tokens and decide whether every OPEN-style marker is matched by a later close marker, using a running counter and early rejection.
Nesting Check for a Token Sequence
A code formatter produces a flat list of string tokens. Two of the tokens control nesting: "INDENT" opens a new nested block, and "DEDENT" closes the most recently opened block. Every other string is an ordinary statement and has no effect on nesting.
Write a function check_nesting(tokens) that returns whether the sequence is well nested.
Rules
Imagine a nesting level that starts at 0. Moving through the list from left to right:
"INDENT"raises the level by 1."DEDENT"lowers the level by 1.- Any other token leaves the level unchanged.
The sequence is well nested if both conditions hold:
- The level never becomes negative at any point. That is, a
"DEDENT"must never appear when the level is already0, regardless of what comes later. - The level is exactly
0after the last token.
Return True if the sequence is well nested, otherwise False.
Details
- An empty list is well nested, so return
True. - Matching is exact and case-sensitive: only the strings
"INDENT"and"DEDENT"(uppercase) affect the level. Strings such as"indent"or"Dedent"are ordinary statements. - Equal numbers of
"INDENT"and"DEDENT"tokens are not sufficient; the order matters.
Input
tokens: a list of strings.
Output
- A boolean:
Trueif the sequence is well nested,Falseotherwise.
Constraints
0 <= len(tokens) <= 2 * 10^5- Each token is a string made up of uppercase and lowercase letters and digits.
Examples
Example 1
Input: check_nesting(['STATEMENT', 'INDENT', 'STATEMENT', 'DEDENT'])
Output: True
Example 2
Input: check_nesting(['INDENT', 'INDENT', 'DEDENT'])
Output: False
Example 3
Input: check_nesting(['DEDENT', 'INDENT'])
Output: False
Hints
Hint 1
Think of INDENT as an opening bracket and DEDENT as a closing bracket, with every other token ignored. How many distinct bracket kinds are there?
Hint 2
Since all open blocks look the same, you do not need to remember which block is open, only how many are open. A single integer is enough.
Hint 3
Check for a negative level immediately after each DEDENT, not only at the end, because a later INDENT could otherwise hide the problem. Finish by testing that the level is exactly 0.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is balanced-bracket checking with only one kind of bracket. Because every open block is interchangeable, a stack would only ever record how many blocks are open, so a single integer level is enough.
Process the tokens from left to right:
"INDENT": increaselevelby 1."DEDENT": decreaselevelby 1. If it becomes negative, returnFalseimmediately.- Anything else: skip it.
After the loop, return level == 0.
Why it is correct
After each token, level equals (INDENT tokens seen so far) minus (DEDENT tokens seen so far). Only a DEDENT can lower it, so checking right after each decrement catches the first prefix where a block is closed without having been opened. That is why ["DEDENT", "INDENT"] is rejected even though the totals match.
If no prefix ever went negative, the only remaining way to be invalid is leaving blocks open, which is exactly the case level > 0 at the end. So the two checks together are necessary and sufficient. Ordinary tokens never change level, and comparison is exact, so lowercase variants are ignored.
Simply comparing the counts of INDENT and DEDENT is wrong because it ignores ordering.
Complexity
- Time: O(n), one pass over the tokens.
- Space: O(1), a single integer.
Reference solution
from typing import List
def check_nesting(tokens: List[str]) -> bool:
level = 0
for token in tokens:
if token == "INDENT":
level += 1
elif token == "DEDENT":
level -= 1
if level < 0:
return False
return level == 0