Problem Description
We are tasked with designing a compressed string iterator. The input is a compressed string where each character is immediately followed by a positive integer indicating how many times that character appears in the uncompressed string. The iterator should implement two methods: next(), which returns the next uncompressed character (or a white space if no characters remain), and hasNext(), which returns true if there are more characters to be iterated.
Key Insights
- Parse the compressed string into segments of (character, count) pairs without decompressing the entire string.
- Use two parallel arrays (or similar data structures) to store characters and their corresponding counts.
- Maintain an index pointer to track the current segment and decrement the count as characters are emitted.
- Handle numbers consisting of multiple digits carefully.
Space and Time Complexity
Time Complexity: O(1) per next() and hasNext() call on average. Space Complexity: O(n), where n is the number of unique character segments in the compressed string.
Solution
The solution first pre-parses the compressed string into a list of character and count pairs. This ensures we do not decompress the entire string, which could be enormous due to high repetition counts. The iterator uses an index pointer to track the current segment and decrements the count each time next() is called. Once a segment’s count is exhausted, the pointer moves to the next segment. Both next() and hasNext() operations run in constant time on average, making the solution efficient.
Code Solutions
All implementations follow a similar approach: parsing the input string to store character segments and counts, then using an index pointer to manage iteration.