Bracket Nesting Check and Rotating Cipher
Stacks & QueuesAuto-graded · 23 test casesLast updated
Tests stack-based bracket validation and modular arithmetic to rotate lowercase letters circularly across the alphabet.
Part 1: Nested Bracket Validation
You are given a string brackets made up exclusively of the six characters (, ), [, ], {, and }. Determine whether the string is properly nested.
A string is properly nested when:
- every opening bracket is eventually closed by a bracket of the same type, and
- brackets are closed in the reverse order they were opened (innermost first).
Return True if the string satisfies both conditions, or False otherwise.
Part 2: Rotating Letter Cipher
You are given a string message containing only lowercase English letters and a non-negative integer rotation. Produce a new string by advancing each character forward by rotation positions in the alphabet. The alphabet wraps around, so advancing 'z' by 1 yields 'a', advancing it by 2 yields 'b', and so on.
Handle arbitrarily large values of rotation without iterating once per unit of shift.
Combined Function
Your function receives brackets, message, and rotation and must return a two-element list:
[<Part 1 result: bool>, <Part 2 result: str>]
The two parts are independent; compute both regardless of each other.
Constraints
0 <= len(brackets) <= 10^4bracketscontains only(,),[,],{,}0 <= len(message) <= 10^4messagecontains only lowercase English lettersa–z0 <= rotation <= 10^9
Examples
Example 1
Input: check_brackets_and_rotate('()[]{}', 'abc', 1)
Output: [True, 'bcd']
Example 2
Input: check_brackets_and_rotate('(]', 'abc', 1)
Output: [False, 'bcd']
Example 3
Input: check_brackets_and_rotate('', 'xyz', 2)
Output: [True, 'zab']
Example 4
Input: check_brackets_and_rotate('{[()]}', 'hello', 26)
Output: [True, 'hello']
Hints
Hint 1
For bracket validation, think about which data structure naturally mirrors the nesting structure: whatever was opened most recently must be closed first. What property does that suggest?
Hint 2
After scanning all of brackets, a single mismatch isn't the only way the string can be invalid — consider what a leftover open bracket means.
Hint 3
A rotation of 26 leaves every letter unchanged, and so does 52, 78, and any multiple of 26. Use that fact to collapse any value of rotation into an equivalent value in the range [0, 25] before you touch a single character.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Bracket Validation
Brackets nest in last-in, first-out order: whichever opening bracket was seen most recently must be the next one closed. That is exactly the behaviour of a stack.
Scan brackets from left to right:
- Opening bracket (
(,[,{): push it onto the stack. - Closing bracket: two things must be true simultaneously — the stack must not be empty (there is something open to close), and the item on top of the stack must be the matching opener. Look up the expected opener in a fixed dictionary:
')' → '(',']' → '[','}' → '{'. If either condition fails, the string is invalid; stop immediately. - After the loop: even if no mismatch occurred mid-scan, any items remaining on the stack represent opening brackets that were never closed. The string is valid only when the stack is empty.
Python's for … else fits naturally: the else branch runs only when the loop completes without hitting break, so it is the right place to perform the final emptiness check.
Why it is correct. The stack always holds, in order, exactly the brackets that have been opened but not yet closed. Popping on every valid match keeps this invariant true throughout the scan. The algorithm therefore checks both ways a string can be invalid: a premature or mismatched close, and an unclosed open.
Key edge cases:
- Empty string — the loop body never runs, the stack stays empty, and the result is
True. - Closing bracket first (e.g.
")") — the stack is empty when the closing bracket arrives, so the result isFalsewithout an index error (checknot stackbefore popping). - Only openers (e.g.
"([") — no mismatch during the scan, but the stack is non-empty at the end, so the result isFalse. Forgetting this final check is the most common bug. - Crossed brackets (e.g.
"([)]") — popping[against)fails immediately, so the result isFalse. A naive counter would incorrectly accept this.
Part 2 — Rotating Letter Cipher
Map each letter to a zero-based index (0 for 'a', 25 for 'z'), add the offset, wrap modulo 26, and map back:
new_char = chr((ord(ch) - ord('a') + offset) % 26 + ord('a'))
Because the alphabet has 26 letters, shifting by any multiple of 26 is a no-op. Compute offset = rotation % 26 once before the loop. After that, every per-character operation involves only values in [0, 25], and the runtime is the same whether rotation is 1 or 10^9.
Why it is correct. Addition modulo 26 is a bijection on {0, …, 25}, so every letter maps to exactly one letter. Wrap-around is automatic: 'z' is 25, and (25 + 1) % 26 = 0, which maps back to 'a'. Reducing the shift up front is safe because (x + r) % 26 == (x + r % 26) % 26 for all integers.
Key edge cases:
- Empty message — the generator produces nothing and the result is
"". rotation = 0or a multiple of 26 —offsetbecomes 0 and every character is unchanged.- Large rotation (10^9) — reduced to
10^9 % 26 = 10before the loop; no performance impact.
Complexity
| Part | Time | Extra space |
|---|---|---|
| Bracket validation | O(n), each character is pushed and popped at most once | O(n) worst case (all openers, e.g. "(((((") |
| Rotating cipher | O(m), one constant-time step per character | O(1) beyond the output string |
Here n = len(brackets) and m = len(message).
Reference Solution
from typing import List
def check_brackets_and_rotate(brackets: str, message: str, rotation: int) -> List:
# Part 1: validate bracket nesting with a stack
closer_to_opener = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in brackets:
if ch in '([{':
stack.append(ch)
elif not stack or stack.pop() != closer_to_opener[ch]:
# Either no open bracket to match against, or wrong type
valid = False
break
else:
# Loop completed without a mismatch; valid iff nothing is left open
valid = not stack
# Part 2: rotate letters, collapsing rotation to [0, 25] first
offset = rotation % 26
rotated = ''.join(
chr((ord(ch) - ord('a') + offset) % 26 + ord('a'))
for ch in message
)
return [valid, rotated]