VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-implement-run-length-encoding-using-linked-lists/

⇱ Program to implement Run Length Encoding using Linked Lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to implement Run Length Encoding using Linked Lists

Last Updated : 11 Jul, 2025

Given a Linked List as the input. The task is to encode the given linked list using Run Length Encoding. That is, to replace a block of contiguous characters by the character followed by it's count. 
For Example, in Run Length Encoding "a->a->a->a->a" will be replaced by "a->5".

Note: For non-repeating nodes, do not append count 1. For example, a->b->b will be replaced by "a->b->2" and not "a->1->b->2".

Examples:

Input : List = a->a->a->a->a->b->r->r->r->NULL 
Output : a->5->b->r->3->NULL 
Explanation :
The character 'a' repeats 5 times. 
The character 'b' repeats 1 time. 
The character 'r' repeats 3 times. 
Hence the output is a->5->b->r->3->NULL.

Input : a->a->a->a->a->a->a->a->a->a->b->r->r->r->a->a->a->NULL 
Output : a->1->0->b->r->3->a->3->NULL 

Approach

  • Traverse through the list.
  • Consider the first character as c.
  • Consider the current character as x.
  • If the character is the same as c then increment the count.
  • If the characters are not same then add the count to the list and append the next character to the list reset the count to 1.

Implementation:


Output
a 3 b r 2 

Complexity Analysis:

  • Time Complexity: O(N2)
  • Auxiliary Space: O(1)

In Place Conversion:

The idea here is to modify the existing list based on the frequency of characters rather than creating a new list if system enforces space constraint. 

  1. Traverse through the list.
  2. Compare current character with the next character. If same then increment the count value.
  3. Delete nodes whose frequency is greater than 2. 
  4. If characters are not same, then update the count value.

Output
a 3 b r 2 

Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(1)
Comment