15% off all plans & roadmaps Use code
See plansDesign Compressed String Iterator
- LeetCode 604
- Easy
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Build an iterator that emits characters from a compressed string on demand instead of expanding it. Keep the current letter, its remaining copies and a pointer to the next group, and load a new group only when the copies run out.
Problem
You are given a compressed string compressedString. Each group is one uppercase or lowercase letter followed by a positive integer. That integer tells you how many times the letter repeats in a row. For example, "a2b3" stands for "aabbb".
Design a class StringIterator with two methods.
next()returns the next character of the uncompressed string. If no characters remain, it returns a single space" ".hasNext()returnstrueif there are more characters to iterate over, andfalseotherwise.
Implement both methods so that you can iterate through the uncompressed string without decompressing the entire string into memory.
Example 1
Input: compressedString = "a10b1c2" Output: ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "c", "c", " "] The output lists the results of fourteen calls to next(), in order.
Constraints
1 <= compressedString.length <= 1000compressedStringconsists of uppercase letters, lowercase letters and digits.- Each count is in the range
[1, 10^9]. - At most 100 calls are made to
nextandhasNext.
Constraints that matter
- The uncompressed length can reach about 500 * 10^9, so the expansion cannot be stored. Each call must produce its character from the compressed input.
- Each count can be 10^9, so the solution cannot loop once per output character. It must jump over whole runs using their counts.
- At most 100 calls are made on a string of at most 1000 characters. A scan of the whole input on every call costs at most 100,000 steps. That makes a rescanning brute force acceptable for this limit.
- Counts can have several digits, such as
a12. The parser must read every digit of a count, not only the first.
Hints
Hint 1
The output is a sequence of runs.
Hint 2
The first idea most people try is to expand the whole string in the constructor.
Solution
Intuition
The output is a sequence of runs. Each run is one letter repeated a known number of times. An iterator answers one question per call: which character comes next. That points to lazy evaluation, where the state holds a cursor into the input and produces each value only when it is asked for.
Picture a stack of index cards, each printed with a letter and a count. The bookmark is ptr, the card you are reading holds the current letter and remaining, and you turn to the next card only when the count hits zero.
What to notice is that the position inside a run is the only extra information you need. If you keep the run's letter and how many copies remain, each next() is a single decrement. Only when that count reaches zero do you need to read the next group from the string.
The groups appear in the string in a fixed order. Parsing never moves backward, so each group is read exactly once across the whole life of the iterator. That is why the cost per call stays small even when the uncompressed string is enormous.
Worked example
Input: compressedString = "a10b1c2" Output: ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "c", "c", " "] Explanation: The string expands to ten a's, one b and two c's, which is 13 characters. The fourteenth call finds nothing left, so it returns a space. The compressed form is only 7 characters long, which is why storing the expansion is wasteful.
Approach 1: Brute force: rescan the groups on every call
The first idea most people try is to expand the whole string in the constructor. That fails here because a single count of 10^9 would need a billion characters in memory.
This version avoids the expansion. It stores only the number of characters already returned, called consumed. Each call walks the groups from the start, subtracting each group's size until the target index falls inside a group.
What is slow: every call starts from the first group, even though the previous call already passed over those groups. The walk repeats the same parsing again and again. The insight that fixes this is that the iterator only moves forward. You can keep a pointer and a remaining count instead of searching from the beginning each time.
Steps
- In the constructor, store the compressed string and set
consumedto 0. - In
locate(k), read groups from left to right: one letter, then all its digits. - Parse the digits into a count. If
kis less than the count, return that letter. - Otherwise subtract the count from
kand move to the next group. - If the walk ends without a match, return a sentinel that means no character.
- In
next(), locate indexconsumed. If a letter is found, incrementconsumedand return it. If not, return a space. - In
hasNext(), return whetherlocate(consumed)finds a letter.
Dry run
Here consumed counts the characters already returned. Calls 1 to 10 locate indexes 0 to 9, which all fall inside the first group a10. At consumed = 10, group a has 10 copies, but 10 < 10 is false, so k becomes 0. Group b has 1 copy, and 0 < 1 is true, so the answer is b.
At consumed = 12, the twelfth index is still a c. Group a leaves k = 2, group b leaves k = 1, and group c with 2 copies matches because 1 < 2. The answer is c.
At consumed = 13, group a leaves 3, group b leaves 2, and group c leaves 0. The walk ends with no match. next() returns a space, and hasNext() returns false.
Complexity
| Time | O(n) per call |
|---|---|
| Space | O(1) extra |
Let n be the length of the compressed string, which is at most 1000. Each call to locate reads each character of the string at most once, and digit parsing adds no extra passes. So one call costs O(n), and the constructor costs O(1) because it only stores a reference. The only extra memory is a few integers, so the extra space is O(1) beyond the input.
PythonTested in our runner
from typing import List, Optional
class StringIterator:
def __init__(self, compressedString: str):
self.s = compressedString
self.consumed = 0 # characters returned so far
def _locate(self, k: int) -> Optional[str]:
# Walk the groups from the start. Return the letter at index k, or None.
i, n = 0, len(self.s)
while i < n:
c = self.s[i]
i += 1
start = i
while i < n and self.s[i].isdigit():
i += 1
cnt = int(self.s[start:i])
if k < cnt:
return c
k -= cnt
return None
def next(self) -> str:
c = self._locate(self.consumed)
if c is None:
return ' '
self.consumed += 1
return c
def hasNext(self) -> bool:
return self._locate(self.consumed) is not NoneThe Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Lazy cursor with remaining countOptimalDesign (General/Specific)
The rescan repeats work. Each call starts at the first group, even though earlier calls already passed those groups. What is slow is walking back to the start on every call. The insight is that the iterator only moves forward, so it can remember where it stopped.
Keep three pieces of state: a pointer ptr into the string, the current letter, and remaining, the copies of that letter still to return. A call with remaining above zero only decrements the count. A call with remaining at zero reads the next group, and it stops only when the pointer reaches the end of the string.
Each group is read once. Parsing its digits costs its digit length, and each digit is read once across the iterator's life. The uncompressed text is never built.
Why it is correct. The state always describes the position right after the last character returned. Groups are read in order and each covers a fixed block of output, so no character is skipped or repeated. Each call advances the state by exactly one character, so the next answer always follows the previous one in the expanded text.
Steps
- Store the compressed string, set
ptrto 0, set the current letter to a space, and setremainingto 0. - In
next(), ifremainingis 0 andptris at the end, return a space. - If
remainingis 0, read the letter atptras the current letter and advanceptr. - Read the digits starting at
ptr, advanceptrpast them, and store their value inremaining. - Decrement
remainingand return the current letter. - In
hasNext(), return true ifremainingis above 0 orptris before the end of the string.
Dry run
Each row shows the state after one call. The pointer moves only when a group loads.
| Call | ptr before | Action | ptr after | letter | remaining after | returned |
|---|---|---|---|---|---|---|
| init | 0 | set state | 0 | space | 0 | |
| next 1 | 0 | load a, parse 10, decrement | 3 | a | 9 | a |
| next 2 | 3 | decrement | 3 | a | 8 | a |
| next 10 | 3 | decrement | 3 | a | 0 | a |
| next 11 | 3 | load b, parse 1, decrement | 5 | b | 0 | b |
| next 12 | 5 | load c, parse 2, decrement | 7 | c | 1 | c |
| next 13 | 7 | decrement | 7 | c | 0 | c |
| hasNext | 7 | remaining 0 and ptr 7 equals length 7 | 7 | c | 0 | false |
| next 14 | 7 | remaining 0 and ptr at end | 7 | c | 0 | space |
The fourteenth call returns a space, which matches the expected output.
Complexity
| Time | O(1) amortized per call |
|---|---|
| Space | O(1) extra beyond the input |
Let n be the length of the compressed string. Each character is read at most once, either as a letter or as a digit, so all group loading over the iterator's life costs O(n). With q calls, the total work is O(n + q), which gives O(1) amortized per call. A single call parses at most 10 digits, because a count of 10^9 has 10 digits, so no call does more than a constant amount of extra work.
PythonTested in our runner
from typing import List, Optional
class StringIterator:
def __init__(self, compressedString: str):
self.s = compressedString
self.ptr = 0 # next unread position in s
self.cur = ' ' # letter currently being emitted
self.remaining = 0 # copies of cur still to return
def next(self) -> str:
if self.remaining == 0:
if self.ptr >= len(self.s):
return ' '
# Load the next group: one letter, then its digits.
self.cur = self.s[self.ptr]
self.ptr += 1
start = self.ptr
while self.ptr < len(self.s) and self.s[self.ptr].isdigit():
self.ptr += 1
self.remaining = int(self.s[start:self.ptr])
self.remaining -= 1
return self.cur
def hasNext(self) -> bool:
return self.remaining > 0 or self.ptr < len(self.s)Common mistakes
- Expanding the groups in the constructor, for example with
res += c * cnt. The inputa1000000000then builds a billion characters. Keep the count and emit one character per call. - Reading the count as a single digit, such as
s[ptr] - '0'. Ona12this returns 1 and then treats the second2as a letter. Loop while the next character is a digit. - Loading the next group before checking
remaining. While copies remain, this overwrites the current letter, soa2would returnaand thenb. Load a group only whenremainingis 0. - Writing
hasNext()as onlyptr < length. Ona3, after the group loads,ptris at the end but two copies remain, so the check returns false too early. Includeremaining > 0. - Reading
s[ptr]innext()without a bounds check after the string ends. Return a space whenptrequals the length andremainingis 0. - Using
k <= cntin the rescanning brute force. Positions run from 0 to cnt minus 1 inside a group, sok <= cntreturns one letter too many.
Edge cases
a1: one character. The firstnext()returnsa, the second returns a space, andhasNext()is false after the first call.A1b1: uppercase and lowercase letters are separate groups. The iterator returnsAthenb, then spaces.a12b3: a two-digit count. The iterator returns twelve a's before the first b, so the digit loop must read both digits.a1000000000: one group with 10^9 copies. Both solutions work without building the string, andhasNext()stays true for a billion calls.a2b3read to the end and past it: the output is a, a, b, b, b, then spaces. Each extra call returns a space, andhasNext()stays false.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Design Compressed String Iterator, with how to answer them.
Unlock the follow-upsDesign Compressed String Iterator FAQ
What is the time complexity of Design Compressed String Iterator?
The lazy cursor runs next() and hasNext() in O(1) amortized time per call. Across the whole life of the iterator, all group parsing totals O(n), where n is the length of the compressed string. The rescanning brute force costs O(n) per call instead.
Why use a lazy cursor for Design Compressed String Iterator?
The problem asks you to produce characters on demand without storing them. A cursor keeps the current letter, its remaining copies and a pointer into the input. Each call moves that state forward by one step, so the full string is never expanded.
Can Design Compressed String Iterator be solved in O(1) extra space?
Yes. The cursor stores a pointer, a letter and a count, which takes the same few variables whatever the uncompressed length is. The input string is the only other storage, and the problem already provides it. The rescanning brute force also uses O(1) extra space.
Why does expanding the string in the constructor fail?
A group such as a1000000000 would need a billion characters in memory. Under this problem's constraints the total uncompressed length can reach about 5 * 10^11, far beyond any memory limit. The iterator must produce each character on demand instead.
Asked at
See which companies ask this — Pro
Related problems
- Design HashMap · same technique: Design (General/Specific)
- Implement Queue using Stacks · same technique: Design (General/Specific)
- Implement Stack using Queues · same technique: Design (General/Specific)
- Logger Rate Limiter · same technique: Design (General/Specific)
- Moving Average from Data Stream · same technique: Design (General/Specific)
- LRU Cache · next harder, same pattern
- Longest Word in Dictionary · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns
- Encode and Decode Strings · same pattern: Design Patterns