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 INPUT Compressed String: L 1 e 2 t 1 C 4 o 1 d 3 e 1 Iterator State: char: 'L' count: 1 index: 0 Methods: next() hasNext() "L1e2t1C4o1d3e1" ALGORITHM STEPS (Parse on Demand) 1 Initialize Store string, set index=0 char=null, count=0 2 next() Called If count=0, parse next char+number from string 3 Return Character Decrement count Return current char 4 hasNext() Check Return true if count>0 or more chars to parse Lazy Parsing Example: next() call 1: parse 'L','1' next() call 2: parse 'e','2' next() call 3: count-- (e) next() call 4: parse 't','1' FINAL RESULT Decompressed Output: L e e t C C C C o d d d e "LeetCCCCoddde" next() Call Sequence: next() --> 'L' (count:1-->0) next() --> 'e' (count:2-->1) next() --> 'e' (count:1-->0) next() --> 't' (count:1-->0) next() --> 'C' x4 next() --> 'o' (count:1-->0) next() --> 'd' x3 next() --> 'e' (count:1-->0) hasNext() --> false OK Key Insight: Parse on Demand: Instead of decompressing the entire string upfront, parse character-count pairs lazily when next() is called. This saves memory O(1) vs O(n) and handles very long compressed strings efficiently. TutorialsPoint - Design Compressed String Iterator | Optimized: Parse on Demand
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