Leetcode #604: Design Compressed String Iterator
In this guide, we solve Leetcode #604 Design Compressed String Iterator in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Design, Array, String, Iterator
Intuition
We need to scan characters while tracking positions or counts.
A simple state machine keeps the logic precise.
Approach
Iterate through the string once and update the state for each character.
Use a map or array if you need fast lookups.
Steps:
- Iterate through characters.
- Maintain necessary state.
- Build or validate the output.
Example
Input
["StringIterator", "next", "next", "next", "next", "next", "next", "hasNext", "next", "hasNext"]
[["L1e2t1C1o1d1e1"], [], [], [], [], [], [], [], [], []]
Output
[null, "L", "e", "e", "t", "C", "o", true, "d", true]
Explanation
StringIterator stringIterator = new StringIterator("L1e2t1C1o1d1e1");
stringIterator.next(); // return "L"
stringIterator.next(); // return "e"
stringIterator.next(); // return "e"
stringIterator.next(); // return "t"
stringIterator.next(); // return "C"
stringIterator.next(); // return "o"
stringIterator.hasNext(); // return True
stringIterator.next(); // return "d"
stringIterator.hasNext(); // return True
Python Solution
class StringIterator:
def __init__(self, compressedString: str):
self.d = []
self.p = 0
n = len(compressedString)
i = 0
while i < n:
c = compressedString[i]
x = 0
i += 1
while i < n and compressedString[i].isdigit():
x = x * 10 + int(compressedString[i])
i += 1
self.d.append([c, x])
def next(self) -> str:
if not self.hasNext():
return ' '
ans = self.d[self.p][0]
self.d[self.p][1] -= 1
if self.d[self.p][1] == 0:
self.p += 1
return ans
def hasNext(self) -> bool:
return self.p < len(self.d) and self.d[self.p][1] > 0
# Your StringIterator object will be instantiated and called as such:
# obj = StringIterator(compressedString)
# param_1 = obj.next()
# param_2 = obj.hasNext()
Complexity
The time complexity is O(n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.