Program to implement run length string decoding iterator class in Python

Run-length encoding compresses data by representing consecutive identical characters as a count followed by the character. This article implements an iterator class that decodes such strings character by character using next() and hasnext() methods.

Problem Understanding

Given a run-length encoded string like "2b1a", we need to create an iterator that can decode it step by step. The string "2b1a" represents "bba" (2 b's followed by 1 a).

Iterator Methods

  • next() − Returns the next character in the decoded sequence
  • hasnext() − Checks if more characters are available

Algorithm Steps

The solution follows these steps ?

  • Parse the encoded string and store count-character pairs
  • In next(), return current character and decrease its count
  • In hasnext(), check if any characters remain

Implementation

class RunLengthIterator:
    def __init__(self, s):
        self.output = []
        num = ""
        for i in s:
            if i.isalpha():
                self.output.append(int(num))
                self.output.append(i)
                num = ""
            else:
                num += i

    def next(self):
        if self.hasnext():
            count = self.output[0]
            letter = self.output[1]
            count -= 1
            if count > 0:
                self.output[0] -= 1
            else:
                self.output = self.output[2:]
            return letter

    def hasnext(self):
        if len(self.output) != 0:
            return True
        return False

# Example usage
s = "2b1a"
obj = RunLengthIterator(s)
print(obj.next())      # First 'b'
print(obj.hasnext())   # Check if more characters exist
print(obj.next())      # Second 'b'
print(obj.next())      # The 'a'
print(obj.hasnext())   # Check if more characters exist

The output of the above code is ?

b
True
b
a
False

How It Works

The constructor parses the input string "2b1a" into pairs: [2, 'b', 1, 'a']. The next() method returns the current character and decrements its count. When a character's count reaches zero, it's removed from the list.

Step-by-Step Execution

Run-Length Iterator Execution Initial: [2, 'b', 1, 'a'] 2 | b | 1 | a After next(): [1, 'b', 1, 'a'] ? 'b' 1 | b | 1 | a After next(): [1, 'a'] ? 'b' 1 | a After next(): [] ? 'a' empty Returns: 'b' Returns: 'b' Returns: 'a' hasnext(): False

Key Features

  • Memory Efficient − Processes characters on-demand without storing the full decoded string
  • Stateful − Maintains current position in the sequence
  • Iterator Pattern − Follows standard iterator interface with next() and hasnext()

Conclusion

This run-length decoding iterator efficiently processes encoded strings character by character. It's memory-efficient since it doesn't decode the entire string upfront, making it suitable for large compressed data streams.

Updated on: 2026-03-26T16:35:31+05:30

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements