Cisco logoCisco
Coding·90 minFree preview

Nested Pattern String Expansion

Expand strings where parenthesized groups are followed by repeat counts in curly braces, including nested groups such as `(a(bc){2}){2}`.

SWE
string
parsing
stack
medium
Frequency
Low
Last asked
2025-08-26
Stage
oa

Requirements

  • Input is one string inputStr.
  • A pattern is a substring enclosed in parentheses, followed by a repeat count enclosed in curly braces.
  • Expand each pattern by concatenating it with itself the requested number of times.
  • Pattern-count pairs can be nested, such as (ef((ab){2}cd){2}){2}.
  • Multi-digit counts can appear.
  • Some inputs may contain spaces; skip irrelevant spaces if the statement permits them.

Examples

Input:

(ab){3}

Output:

ababab

Input:

(a(bc){2}){2}

Output:

abcbcabcbc

Notes

  • A stack-based parser is the natural fit: keep the string accumulated before (, parse the substring up to ), read the following {number}, then repeat and append.
  • Java candidates hit errors when comparing char to String, for example using != "}" instead of comparing against '}'.
  • Hidden cases can stress nested groups and multi-digit repeat counts.
  • Stack version: on ( push the current buffer and start a new one; on ) read the following {k} (accumulating every digit), pop the outer buffer, and append the inner buffer repeated k times. O(output length) time.
  • Same family as the bracket-decoding problem k[...], except the count comes after the group in {} instead of before it.

Preparation

  • Implement the stack expander in 20 minutes and test (ab){3}, (a(bc){2}){2}, (ef((ab){2}cd){2}){2}, a two-digit count such as (a){12}, and an input with text outside any group.
  • Solve the classic k[...] bracket-decoding problem, then adapt it to the (...){k} syntax and compare the two parsers.
  • Drill LC 394 for the bracket-decoding family.
Was this article helpful?

Comments

Sign in to join the discussion
Loading...