Design Compressed String Iterator - Problem

Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.

Implement the StringIterator class:

  • StringIterator(String compressedString): Initializes the object with a compressed string.
  • next(): Returns the next character if the original string still has uncompressed characters, otherwise returns a white space ' '.
  • hasNext(): Returns true if there is any letter needs to be uncompressed in the original string, otherwise returns false.

Input & Output

Example 1 — Basic Compression
$ Input: compressedString = "L1e2t1C4o1d3e1"
Output: LeetCCCCoddde
💡 Note: L appears 1 time, e appears 2 times, t appears 1 time, C appears 4 times, o appears 1 time, d appears 3 times, e appears 1 time
Example 2 — Single Character
$ Input: compressedString = "x5"
Output: xxxxx
💡 Note: Character x appears 5 times consecutively
Example 3 — Mixed Case
$ Input: compressedString = "A2b3C1"
Output: AAbbbC
💡 Note: A appears 2 times, b appears 3 times, C appears 1 time

Constraints

  • 1 ≤ compressedString.length ≤ 1000
  • compressedString consists of lowercase and uppercase English letters and digits
  • The number after each character is in the range [1, 999]

Visualization

Tap to expand
Compressed String Iterator DesignInputL1e2t1C4Iterator StateCurrent: (L, 1) → (e, 2) → (t, 1) → (C, 4)OutputL e e t C C C Cnext() Method1. Return current char2. Decrement count3. Move to next pairhasNext() MethodCheck if morecharacters remainin current/next pairsSpace EfficiencyStore pairs: O(k)Not full string: O(n)k ≪ n for repetitionIterator maintains current position without expanding entire stringMemory: O(groups) instead of O(total characters)
Understanding the Visualization
1
Input Format
Compressed string with character followed by count
2
Iterator Design
Track current character and remaining count
3
Output Generation
Return characters one by one until exhausted
Key Takeaway
🎯 Key Insight: Parse compressed format into character-count pairs and track current state dynamically, avoiding memory waste from full expansion.
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 25
34.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen