Compressed Word Check Plus Bracket Matching
StringsAuto-graded · 25 test casesLast updated
Tests two linear scans in one function: validating a numeric-skip word abbreviation with two pointers, and checking nested bracket balance with a stack.
Write a single function that answers two independent yes/no questions and returns both answers in a list.
Part A: Is the shortened form legitimate?
You are given a lowercase string word and a string abbr. Decide whether abbr is a valid shortened form of word, using these rules while reading abbr from left to right:
- A letter in
abbrstands for itself. It must equal the next not-yet-covered character ofword. - A maximal run of consecutive digits in
abbris read as one decimal numberk. It stands forkconsecutive characters ofword, whose contents are ignored. - Every such number must be positive and must not start with the digit
0. So"0","01", and"a05b"are all invalid. - The shortened form is valid only if, once all of
abbrhas been read, it has covered every character ofwordexactly, with no characters left over and none overshot.
Part B: Are the brackets balanced?
You are given a string s made up only of the characters (, ), [, ], {, }. It is balanced when:
- Every opening bracket is closed by a bracket of the same kind.
- Brackets are closed in the correct nesting order (the most recently opened unclosed bracket must be closed first).
- The empty string is balanced.
Output
Return a list of two booleans: [abbr_ok, brackets_ok], where abbr_ok is the answer to Part A and brackets_ok is the answer to Part B.
Constraints
wordcontains only lowercase English letters and may be empty.abbrcontains only lowercase English letters and digits, and may be empty.scontains only the six bracket characters above and may be empty.- Numbers in
abbrmay be large; do not build the expanded string, simply move a pointer by that amount. - The two parts are independent of each other.
Examples
Example 1
Input: check_abbreviation_and_brackets('internationalization', 'i12iz4n', '()[]{}')
Output: [True, True]
Example 2
Input: check_abbreviation_and_brackets('apple', 'a2e', '([)]')
Output: [False, False]
Example 3
Input: check_abbreviation_and_brackets('', '', '')
Output: [True, True]
Hints
Hint 1
For the abbreviation, keep one pointer into `word` and one into `abbr`. A letter advances both after a comparison; a number advances only the `word` pointer by its value.
Hint 2
When you meet a digit, check whether it is '0' first (that rejects both a bare zero and leading zeros), then keep reading digits to form the whole number before moving the word pointer. Stop early if the pointer runs past the end of `word`.
Hint 3
For brackets, push openers on a stack; on a closer, the stack must be non-empty and its top must be the matching opener. At the end the stack must be empty. Don't forget the final full-consumption check in the abbreviation part.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two questions are independent, so each is solved with its own linear scan and the results are returned together.
Part A: abbreviation check (two pointers)
Keep wi, the next uncovered position in word, and ai, the next unread position in abbr.
- If
abbr[ai]is a digit:- If it is
'0', the abbreviation is invalid. This covers a bare0and any number with a leading zero. - Otherwise read the whole run of digits into one number and add it to
wi. Ifwinow exceedslen(word), the abbreviation overshoots and is invalid. Landing exactly onlen(word)is fine, since an abbreviation may end with a number.
- If it is
- If it is a letter,
wimust still be inside the word andword[wi]must equal the letter. Then advance both pointers.
After the loop, the abbreviation is valid only if no failure occurred and wi == len(word), so nothing in the word is left uncovered.
Part B: balanced brackets (stack)
Push each opening bracket. For each closing bracket, the stack must be non-empty and its top must be the matching opener; pop it. At the end the stack must be empty, otherwise some openers were never closed.
Why it is correct
An abbreviation describes the word from left to right with exactly one possible alignment: each letter covers one character and each number covers exactly that many. The scan simply follows that alignment, so no backtracking is needed, and the final check ensures the whole word is covered.
Correct bracket nesting means the most recently opened, still-open bracket must be closed first, which is exactly last-in, first-out behavior. The empty-stack check on a closer rejects inputs like ")", and the final empty-stack check rejects inputs like "((". An empty string never pushes anything, so it is valid.
Complexity
With m = len(abbr) and k = len(s):
- Time: O(m + k). Skips are applied arithmetically, never by walking the skipped characters.
- Space: O(k) for the stack in the worst case; the abbreviation part uses O(1).
Reference solution
from typing import List
def check_abbreviation_and_brackets(word: str, abbr: str, s: str) -> List[bool]:
# Part A: two-pointer scan of the abbreviation
wi = 0
ai = 0
abbr_ok = True
while ai < len(abbr):
ch = abbr[ai]
if ch.isdigit():
if ch == '0':
abbr_ok = False
break
num = 0
while ai < len(abbr) and abbr[ai].isdigit():
num = num * 10 + int(abbr[ai])
ai += 1
wi += num
if wi > len(word):
abbr_ok = False
break
else:
if wi >= len(word) or word[wi] != ch:
abbr_ok = False
break
wi += 1
ai += 1
abbr_ok = abbr_ok and wi == len(word) and ai == len(abbr)
# Part B: stack-based bracket matching
match = {')': '(', ']': '[', '}': '{'}
stack = []
brackets_ok = True
for c in s:
if c in '([{':
stack.append(c)
elif not stack or stack.pop() != match[c]:
brackets_ok = False
break
brackets_ok = brackets_ok and not stack
return [abbr_ok, brackets_ok]