Run-Length Encoding (RLE) is a simple data compression technique that reduces the size of data by replacing consecutive occurrences of the same character with the character followed by its frequency. Instead of storing every repeated character individually, the encoding technique stores the character once along with the number of consecutive occurrences.
For example, the string AAABBCDDDD can be represented as A3B2C1D4.
In Java, this problem can be solved using string manipulation, character comparison, loops and a counter variable. Let us understand the concept, develop the algorithm, write the Java program and examine its working through examples and a detailed dry run.
What Is Run-Length Encoding?
Run-Length Encoding is a lossless data compression technique in which consecutive identical characters are replaced by a single occurrence of the character followed by its frequency. For example, consider the string:
AAABBCDDDD
It can be divided into the following groups:
- AAA becomes A3
- BB becomes B2
- C becomes C1
- DDDD becomes D4
Therefore, the encoded string is:
A3B2C1D4
The original string contains 10 characters, whereas the encoded string contains 8 characters. Hence, compression is achieved.
Important: The frequency must always be written, even when a character occurs only once. Therefore, C is represented as C1 and not simply C. Consider another example:
ABCD
Since no character is repeated consecutively, the encoded form becomes:
A1B1C1D1
The encoded string is longer than the original string. Therefore, no compression is achieved.
Algorithm for Run-Length Encoding
The program follows a systematic approach to identify consecutive groups of identical characters and calculate their frequencies.
Step-by-step algorithm:
- Start.
- Accept a string S from the user.
- Calculate the length L of the string.
- Check whether L is between 1 and 60.
- If the length is invalid, display INVALID INPUT and terminate.
- Traverse the string and check whether every character is an uppercase letter between A and Z.
- If any character is invalid, display INVALID INPUT and terminate.
- Initialize an empty string enc and a counter variable count with 1.
- Traverse the string from the first character up to the second-last character.
- Compare the current character with the next character.
- If both characters are identical, increment count.
- Otherwise:
- Append the current character and its count to enc.
- Reset count to 1.
- Append the last character and its count to enc.
- Display the encoded string.
- Display the original length and encoded length.
- If the encoded length is less than the original length, display Compression achieved.
- Otherwise, display No compression achieved.
- Stop.
Java Program for Run-Length Encoding
The following Java program uses the Scanner class, string manipulation methods and a counter variable to implement Run-Length Encoding.
import java.util.Scanner;
public class RunLength
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
int l = s.length();
// Check validity of input
if(l < 1 || l > 60)
{
System.out.println("INVALID INPUT");
System.exit(0);
}
for(int i = 0; i < l; i++)
{
char ch = s.charAt(i);
if(ch < 'A' || ch > 'Z')
{
System.out.println("INVALID INPUT");
System.exit(0);
}
}
String enc = "";
int count = 1;
for(int i = 0; i < l - 1; i++)
{
if(s.charAt(i) == s.charAt(i + 1))
{
count++;
}
else
{
enc = enc + s.charAt(i) + count;
count = 1;
}
}
// Append the last character and its count
enc = enc + s.charAt(l - 1) + count;
System.out.println("Encoded String : " + enc);
System.out.println("Original Length: " + l + ", Encoded Length: " + enc.length());
if(enc.length() < l)
System.out.println("Compression achieved");
else
System.out.println("No compression achieved");
}
}Explanation of the Program
Input Validation
The program first accepts a string and calculates its length.
int l = s.length();
if(l < 1 || l > 60)
{
System.out.println("INVALID INPUT");
System.exit(0);
}The input string must contain at least one character and a maximum of 60 characters.
The next loop checks whether every character belongs to the uppercase English alphabet.
for(int i = 0; i < l; i++)
{
char ch = s.charAt(i);
if(ch < 'A' || ch > 'Z')
{
System.out.println("INVALID INPUT");
System.exit(0);
}
}The condition ch < 'A' || ch > 'Z' rejects lowercase letters, digits, spaces and special characters.
Initializing the Variables
String enc = "";
int count = 1;Two variables are initialized:
encstores the final encoded string.countmaintains the frequency of consecutive identical characters.
The counter starts at 1 because every character occurs at least once.
Comparing Consecutive Characters
This is the most important part of the program.
for(int i = 0; i < l - 1; i++)
{
if(s.charAt(i) == s.charAt(i + 1))
{
count++;
}
else
{
enc = enc + s.charAt(i) + count;
count = 1;
}
}The loop compares the current character with the next character.
There are two possible situations:
Case 1: Both characters are identical
If the current character and the next character are equal, the counter is incremented.
if(s.charAt(i) == s.charAt(i + 1))
{
count++;
}Case 2: Both characters are different
When two consecutive characters are different, the current group has ended.
else
{
enc = enc + s.charAt(i) + count;
count = 1;
}The current character and its frequency are appended to the encoded string. The counter is then reset to 1 for the next group.
Understanding the Important Loop
Consider the following statement:
for(int i = 0; i < l - 1; i++)This is an important part of the program because it prevents an index-out-of-bounds error.
Let us understand its components:
int i = 0: The loop begins with the first character.i < l - 1: The loop continues only up to the second-last character.i++: The index increases by 1 after every iteration.
The program compares:
s.charAt(i) == s.charAt(i + 1)Therefore, the loop must not reach the last index because accessing i + 1 would exceed the valid string index.
Why Is the Last Character Appended Separately?
Consider the statement:
enc = enc + s.charAt(l - 1) + count;The main loop processes only up to the second-last character. When the loop terminates, the frequency of the final group is already stored in the counter variable. For example, consider:
AAABBCDDDD
After processing the comparisons, the encoded string contains:
A3B2C1
The final group consists of four consecutive D characters. Its frequency is stored in count as 4.
Therefore, the last statement appends:
D4
The final encoded string becomes:
A3B2C1D4
Remember: The last character must be appended separately because the loop does not process it as the current character.
Sample Executions
Execution 1: Compression Achieved
Input:
AAABBCDDDDOutput:
Encoded String : A3B2C1D4
Original Length: 10, Encoded Length: 8
Compression achievedExplanation: The original string contains 10 characters, while the encoded string contains only 8 characters. Therefore, compression is achieved.
Execution 2: No Compression Achieved
Input:
ABCDOutput:
Encoded String : A1B1C1D1
Original Length: 4, Encoded Length: 8
No compression achievedExplanation: Every character occurs only once. Consequently, each character is followed by 1, increasing the length of the encoded string.
Execution 3: Handling a Two-Digit Frequency
Input:
WWWWWWWWWWWWBWWWOutput:
Encoded String : W12B1W3
Original Length: 16, Encoded Length: 7
Compression achievedExplanation: The first group contains 12 consecutive W characters, followed by one B and three W characters. Notice that the frequency 12 occupies two characters in the encoded string.
Execution 4: Invalid Input
Input:
AAbbOutput:
INVALID INPUTExplanation: The input contains lowercase letters. Since only uppercase letters are permitted, the program terminates after displaying the error message.
Dry Run for S = AAABBCDDDD
Let us understand the execution of the program by tracing each iteration of the loop.
Given:
S = AAABBCDDDD
L = 10
Initially:
- enc = “”
- count = 1
The loop executes with i taking the values from 0 to 8 because the condition is i < l - 1.
Dry Run Table
| i | Current Character | Next Character | Comparison | Count | Encoded String |
|---|---|---|---|---|---|
| 0 | A | A | Equal | 2 | |
| 1 | A | A | Equal | 3 | |
| 2 | A | B | Different | 1 | A3 |
| 3 | B | B | Equal | 2 | A3 |
| 4 | B | C | Different | 1 | A3B2 |
| 5 | C | D | Different | 1 | A3B2C1 |
| 6 | D | D | Equal | 2 | A3B2C1 |
| 7 | D | D | Equal | 3 | A3B2C1 |
| 8 | D | D | Equal | 4 | A3B2C1 |
After completing the loop, the last character and its count are appended.
enc = enc + s.charAt(l - 1) + count;Therefore:
enc = A3B2C1D4
Explanation of Each Important Iteration
Iteration 1:
- i = 0
- Current character = A
- Next character = A
- Both characters are identical.
- Therefore, count becomes 2.
Iteration 2:
- i = 1
- Current character = A
- Next character = A
- Both characters are identical.
- Therefore, count becomes 3.
Iteration 3:
- i = 2
- Current character = A
- Next character = B
- Both characters are different.
- Therefore, A3 is appended to enc.
- The counter is reset to 1.
Iteration 4:
- i = 3
- Current character = B
- Next character = B
- Both characters are identical.
- Therefore, count becomes 2.
Iteration 5:
- i = 4
- Current character = B
- Next character = C
- Both characters are different.
- Therefore, B2 is appended to enc.
- The counter is reset to 1.
Iteration 6:
- i = 5
- Current character = C
- Next character = D
- Both characters are different.
- Therefore, C1 is appended to enc.
- The counter remains 1.
Iterations 7, 8 and 9:
The current character and next character are both D.
The counter increases from 2 to 4.
Finally, D4 is appended separately.
Final Output
Encoded String : A3B2C1D4
Original Length: 10, Encoded Length: 8
Compression achievedImportant Concepts Used in the Program
| Java Concept | Purpose |
| length() | Calculates the length of the string |
| charAt() | Accesses individual characters |
| for loop | Traverses the string |
| if-else | Compares consecutive characters |
| == operator | Compares consecutive characters |
| Counter variable | Calculates the frequency of characters |
| String concatenation | Constructs the encoded string |
| System.exit(0) | Terminates the program for invalid input |
Why Is the Counter Initialized to 1?
Consider the statement:
int count = 1;Every character occurs at least once in its own group. Therefore, the counter starts at 1 rather than 0.
For example, in the string ABCD, each character occurs once. Hence, the encoded form must be A1B1C1D1.
Why Is enc.length() Used?
Consider:
WWWWWWWWWWWWBWWW
Its encoded form is:
W12B1W3
The frequency 12 occupies two characters. Therefore, the encoded length must be calculated using:
enc.length()It cannot be calculated simply by counting the number of character groups.
Important Examination Tips
Students should remember the following points while writing this program in their ISC practical examination:
- Always validate the length of the input before processing it.
- Check that every character is an uppercase English letter.
- Initialize the counter to 1 because every group contains at least one character.
- Compare the current character with the next character using
charAt(). - Increment the counter when consecutive characters are identical.
- Append the character and its frequency when a different character is encountered.
- Reset the counter to 1 after completing a group.
- Append the last character and its frequency separately.
- Use
enc.length()to calculate the actual encoded length. - Compression is achieved only when the encoded length is strictly less than the original length.
Conclusion
The Run-Length Encoding program is an excellent practical examination problem that tests a student’s understanding of string manipulation, character comparison, loops, conditional statements and counter variables. The most important part of the solution is identifying when a group of identical consecutive characters ends. The character and its frequency are then appended to the encoded string, and the counter is reset for the next group.
By understanding the algorithm, important loop conditions and dry run, students can confidently solve similar programming problems involving strings and basic data compression techniques.
Important Viva Questions and Answers
Q1. What is Run-Length Encoding?
Run-Length Encoding is a lossless data compression technique that replaces consecutive identical characters with a single character followed by its frequency.
Q2. What is the encoded form of AAABBB?
The encoded form is A3B3.
Q3. Why is the frequency written even when a character occurs only once?
Because the problem specifically requires every group to be followed by its frequency, including groups containing a single character.
Q4. Why is count initialized to 1?
Because every character occurs at least once in its own group.
Q5. Why is the loop executed only up to l – 1?
Because the program compares the current character with the next character using charAt(i + 1). Processing the last index would cause an index-out-of-bounds error.
Q6. Why is the last character appended separately?
The loop processes only up to the second-last character. Therefore, the final group must be appended after the loop.
Q7. What is the purpose of count = 1?
It resets the counter when a new group of characters begins.
Q8. Why is charAt() used?
The charAt() method accesses an individual character at a specified index in a string.
Q9. What is the purpose of the condition ch < ‘A’ || ch > ‘Z’?
It checks whether a character falls outside the uppercase English alphabet.
Q10. Can Run-Length Encoding increase the size of a string?
Yes. For example, ABCD becomes A1B1C1D1, increasing the length from 4 to 8.
Q11. What is meant by lossless compression?
Lossless compression is a technique in which the original data can be reconstructed exactly from the compressed representation.
Q12. Why is enc.length() used instead of the number of character groups?
Because the frequency may contain multiple digits. For example, W12 occupies three characters, not two.
Q13. What happens if the input contains lowercase letters?
The program displays INVALID INPUT and terminates.
Q14. What is the maximum permitted length of the input string?
The maximum permitted length is 60 characters.
Q15. What is the time complexity of the algorithm?
The algorithm has O(n) time complexity because the string is traversed a constant number of times, where n is the length of the input string.
Q16. Is Run-Length Encoding suitable for every type of string?
No. It is more effective when the string contains long sequences of consecutive repeated characters. For strings with mostly distinct characters, the encoded representation may become longer.