VOOZH about

URL: https://www.geeksforgeeks.org/dsa/run-length-encoding/

⇱ Run Length Encoding and Decoding - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Run Length Encoding and Decoding

Last Updated : 9 May, 2026

Given a string s, implement a function encode that performs run-length encoding on the string. Run-length encoding is a form of compression where consecutive occurrences of the same character are replaced by the character followed by the count of its occurrences.

Input: s = aaaabbbccc
Output: a4b3c3
Explanation: The character 'a' repeated 4 times consecutively and 'b' 3 times, 'c' also 3 times, so answer for this test case is a4b3c3.

Input: s = abbbcdddd
Output: a1b3c1d4
Explanation: The character 'a' is repeated 1 time, 'b' 3 times, 'c' 1 time and 'd' repeated 4 times, so answer for this test case is a1b3c1d4.

Using Iteration (Run-Length Encoding) - O(n) Time and O(n) Space

Follow the steps below to solve this problem:

  1. Pick the first character from the source string. 
  2. Append the picked character to the destination string. 
  3. Count the number of subsequent occurrences of the picked character and append the count to the destination string. 
  4. Pick the next character and repeat steps 2, 3 and 4 if the end of the string is NOT reached.

Below is the implementation of the above approach:


Output
w4a3d1e1x6y1w3
Comment