KatInterview

Bracket Nesting Check and Rotating Cipher

Stacks & QueuesAuto-graded · 23 test cases
MediumAuto-gradedStacks & Queuesstacksstringsmodular-arithmetic

Last 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^4
  • brackets contains only (, ), [, ], {, }
  • 0 <= len(message) <= 10^4
  • message contains only lowercase English letters a–z
  • 0 <= 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.