BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP35 of 38 in topic

831. Expand a compressed string with counts and nested groups

MediumTokenization and NLP Pro

A compact format writes repeated text with counts. A count is a positive integer (it can have several digits) and applies only to the item right after it. An item is either one lowercase letter or a group in parentheses, and groups can nest. An item with no count appears once.

Write expand(s) that returns the fully expanded string. The input is always well formed.

Functiondef expand(s)

Example 1

Input: expand("3b")

Output: "bbb"

Example 2

Input: expand("2a2(a3(b))")

Output: "aaabbbabbb": 2a gives "aa", the group a3(b) gives "abbb", and it repeats twice

Constraints

  • len(s) <= 200
  • Output length <= 100,000
  • Input is well formed.
Hint 1

Read every digit before the item.

Hint 2

A "(" starts a recursive call that ends at the matching ")".

Hint 3

Default the count to 1.

Common mistakes
  • Treating each digit as its own count, so "12x" becomes wrong.
  • Applying a count to everything after it instead of only the next item.
  • Forgetting to skip the closing parenthesis after a group.
Understand the idea

Nested repeat formats are parsed with recursion or an explicit stack. The key detail here is that a count binds only to the next item, so "2a2(a3(b))" means aa followed by two copies of (a followed by bbb). With a stack you push the current partial string and pending count on "(" and on ")" pop, repeat and append. Multi-digit counts must be built as count * 10 + digit.

Topics
Tokenization and NLP
Similar questions
  • Do one merge step of a BPE tokenizerMedium
  • Compute Levenshtein edit distanceMedium
  • Tokenize words with WordPiece greedy longest matchMedium
  • Build a vocabulary with special tokens, a minimum frequency and UNKMedium
All Tokenization and NLP problems
Report
831 / 903
Python 3solution.pyPython idle
1
2
3
4
def expand(s):
# return the expanded string
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS