🌐
GeeksforGeeks
geeksforgeeks.org › dsa › valid-compressed-string
Valid Compressed String - GeeksforGeeks
August 28, 2026 - We maintain a pointer j in the original string s. When we encounter consecutive digits in t, we combine them into one number and skip that many characters in s. When we encounter a character, it must match the current character of s. If any mismatch occurs or a skip goes beyond the end of s, the compression is invalid.
Python map() function
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Enumerate() in Python
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Read JSON file using Python
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Adding New Column to Existing DataFrame in Pandas
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
🌐
GeeksforGeeks
geeksforgeeks.org › problems › easy-string2212 › 1
Compress String | Practice | GeeksforGeeks
Given a string s, compress it by replacing each group of consecutive identical characters with the lowercase character followed by its frequency. Uppercase and lowercase versions of the same letter are treated as identical. If the same character a
🌐
GeeksforGeeks
geeksforgeeks.org › problems › valid-compressed-string--170647 › 1
Valid Compressed String | Practice | GeeksforGeeks
During compression, any sequence of consecutive characters may be replaced by the number of characters removed. If t contains consecutive digits, treat them as a single number. For example, "B32" represents "B" + "32", not "B" + "3" + "2". ... ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › compressing-string-in-javascript
Compressing String in JavaScript - GeeksforGeeks
August 5, 2025 - Compressing a string involves replacing repeated characters with their count followed by the character itself.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › check-if-string-s-can-be-compressed-to-t-by-replacing-some-x-characters-with-count-x
Check if String S can be compressed to T by replacing some X characters with count X - GeeksforGeeks
July 23, 2025 - Note: A compression mechanism can arbitrarily delete X (X >= 0) characters and replace them with the deleted character count (X). ... Input: S = "HELLOWORLD" T="H2L4L1" Output: True Explanation: Replace index 1 to 2 in "HELLOWORLD" with count 2 -> "H2LOWORLD" Replace index 4 to 7 in "HELLOWORLD" with count 4 -> "H2L4LD" Replace index 9 in "HELLOWORLD" with count 1 -> "H2L4L1" The resultant string is same as T.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › length-of-minimized-compressed-string
Length of minimized Compressed String - GeeksforGeeks
July 23, 2025 - If S = "ABCDABCD", then the string can be compressed as (ABCD)2, so the length of the compressed string will be 4.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › compressed-string-decoding-for-kth-character
Compressed String decoding for Kth character - GeeksforGeeks
July 23, 2025 - The idea is to generate the expanded string and then find the Kth value of that string. To do so we will use a string "decoded" and insert the compressed string when encounter a string and if we encounter a digit then we will multiply the string ...
🌐
Glassdoor
glassdoor.co.in › expedia group interviews
Expedia Group Interview Question: String compression (I think this problem is on LeetCode). https://www.geeksforgeeks.org/count-the-number-of-ways-to-divide-n-in-k-groups-incrementally/ (the second coding one) | Glassdoor
Interview question for Software Engineer. String compression (I think this problem is on LeetCode). https://www.geeksforgeeks.org/count-the-number-of-ways-to-divide-n-in-k-groups-incrementally/ (the second coding one) .
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › run-length-encoding
Run Length Encoding and Decoding - GeeksforGeeks
1 week ago - Given a string s, implement a function ... 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....
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › gzip-compresss-in-python
gzip.compress(s) in Python - GeeksforGeeks
March 23, 2020 - With the help of gzip.compress(s) method, we can get compress the bytes of string by using gzip.compress(s) method.
🌐
LeetCode
leetcode.com › problems › string-compression
String Compression - LeetCode
String Compression - Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: * If the group's length is 1, append the character ...
🌐
YouTube
youtube.com › watch
String Compression Leetcode(Medium) in JAVA | Explanation and Code - YouTube
Please consume this content on nados.pepcoding.com for a richer experience. It is necessary to solve the questions while watching videos, nados.pepcoding.com...
Published: September 29, 2020
🌐
Educative
educative.io › answers › what-is-the-string-compression-algorithm
What is the string compression algorithm?
The string should be compressed such that consecutive duplicates of characters are replaced with the character and followed by the number of consecutive duplicates.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-program-to-return-original-string-of-compressed-string
JavaScript Program to Return Original String of Compressed String - GeeksforGeeks
April 1, 2024 - The compressed string follows a format where each character is followed by its count. we need to print a string having the same number of characters present in the compressed string.
🌐
GitHub
github.com › MAZHARMIK › Interview_DS_Algo › blob › master › strings › String Compression.cpp
Interview_DS_Algo/strings/String Compression.cpp at master · MAZHARMIK/Interview_DS_Algo · GitHub
Leetcode Link : https://leetcode.com/problems/string-compression/ GfG Link : https://practice.geeksforgeeks.org/problems/run-length-encoding/1 ·
Author: MAZHARMIK
🌐
Waiting4you
waiting4you.it › string-compression-python-geeksforgeeks.html
String compression python geeksforgeeks
Find Complete Code at GeeksforGeeks Article: http://www.geeksforgeeks.org/python-language-introduction/This video is contributed by Parikshit Kumar PruthiPle... ... Compression worked example: For example, if the string "AABAABAA" was being compressed, then: 1.
🌐
GeeksforGeeks
geeksforgeeks.org › computer networks › lzw-lempel-ziv-welch-compression-technique
LZW (Lempel–Ziv–Welch) Compression technique - GeeksforGeeks
July 23, 2025 - LZW compression works by reading a sequence of symbols, grouping the symbols into strings, and converting the strings into codes. Because the codes take up less space than the strings they replace, we get compression.
🌐
Rybacki
jxda.rybacki.fr › string-compression-geeksforgeeks.html
String Compression Geeksforgeeks
Loop through the array of strings For each string, first sort its characters, using the sorted string as key and original string as value, put into a hash table. Implementing this operation is immediate, using a priority queue. We used static compression for our Javascript and CSS. Domain Name: GEEKSFORGEEKS.
🌐
AlgoMonster
algo.monster › home › 443. string compression
443. String Compression - In-Depth Explanation
The characters in the array beyond the returned length can contain any values and should be ignored. Only the first k characters (where k is the returned length) represent the compressed result.
Top answer
1 of 4
11

As @vnp said, don't print the result for "testing". Convert each statement in the main method to proper unit tests, for example:

@Test
public void test_aabcccccaaa() {
    assertEquals("a2b1c5a3", compress("aabcccccaaa"));
}

@Test
public void test_a5() {
    assertEquals("a5", compress("aaaaa"));
}

Once this is done, you can go ahead and safely refactor the rest of the code, having an easy way to repeat the tests.

Being aware of, and working knowledge of unit testing should definitely score you extra points in a job interview, or might be even required.

Bug

For single letter inputs, the method seems to return an empty string. That looks incorrect. Judging by that for "abc" it returns "a1b1c1", it would seem that for "a" it should return "a1" instead of an empty string

Simplify

The algorithm can be simplified to these steps:

  • Loop over the characters, from the 2nd till the end
  • If the current character is the same as the previous, increment the count
  • If different, append the count and append the previous character
  • After the end of the loop, append the count

The implementation can be something like this:

public String compress(String str) {
    if (str.isEmpty()) {
        return "";
    }

    char[] chars = str.toCharArray();
    StringBuilder builder = new StringBuilder();

    int count = 1;
    char prev = chars[0];
    for (int i = 1; i < chars.length; i++) {
        char current = chars[i];
        if (current == prev) {
            count++;
        } else {
            builder.append(prev).append(count);
            count = 1;
        }
        prev = current;
    }
    return builder.append(prev).append(count).toString();
}
2 of 4
3

Order of expressions in if statement

Your code would be more readable if you would be consistent with your ordering in the if clause. You have

str.charAt(i) == str.charAt(i - 1) && i < str.length() - 1

but:

i == str.length() - 1 && str.charAt(i) == str.charAt(i - 1)

instead of:

str.charAt(i) == str.charAt(i - 1) && i == str.length() - 1

Last Loop

You have two conditions that only apply in the last loop. I would pull those out to after the loop:

public static String compress(String str) {
    int count = 1;
    StringBuilder builder = new StringBuilder();

    for (int i = 1; i < str.length() - 1; i++) {
        if (str.charAt(i) == str.charAt(i - 1)) {
            count++;
        } else {
            builder.append(str.charAt(i - 1));
            builder.append(count);
            count = 1;
        }
    }
    // special cases for last chars
    if (str.length() > 1) {
        if (str.charAt(str.length() - 1) == str.charAt(str.length() - 2)) {
            count++;
        } else {
            builder.append(str.charAt(str.length() - 2));
            builder.append(count);
            count = 1;
        }
        builder.append(str.charAt(str.length() - 1));
        builder.append(count);
    }
    return builder.toString();
}