KatInterview

Check Block Nesting in a Flat Marker Sequence

Stacks & QueuesAuto-graded · 23 test cases
EasyAuto-gradedStacks & Queuescounterbalanced-bracketssingle-pass

Last 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:

  1. The level never becomes negative at any point. That is, a "DEDENT" must never appear when the level is already 0, regardless of what comes later.
  2. The level is exactly 0 after 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: True if the sequence is well nested, False otherwise.

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.