Start learning free

LESSON 28 OF 68 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in Java: Squeeze Repeated Characters

Practice Read the full explanation

Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.

Function signature:

public String trSqueeze(List<String> lines, String chars)

Example:

Input: lines = ["aaabbb", "abaa"], chars = "a"

Output: "abbb\naba"

When printed:
abbb
aba

Put each char of chars into a HashSet<Character>. Walk each line tracking char prev = '\0'; skip the current char only if it's in the set AND equals prev.

The full solution:
class Solution {
    public String trSqueeze(List<String> lines, String chars) {
        Set<Character> squeeze = new HashSet<>();
        for (int i = 0; i < chars.length(); i++) {
            squeeze.add(chars.charAt(i));
        }
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            StringBuilder sb = new StringBuilder();
            char prev = '\0';
            for (int j = 0; j < line.length(); j++) {
                char ch = line.charAt(j);
                if (squeeze.contains(ch) && ch == prev) {
                    continue;
                }
                sb.append(ch);
                prev = ch;
            }
            result.add(sb.toString());
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 15
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Java, explained

    Problem overview

    The fourth version of the tr tool behaves like tr -s. The method trSqueeze(List<String> lines, String chars) collapses each run of the same character into a single occurrence, but only for characters that appear in chars. Everything else is left alone. The lines are joined by \n.

    chars is a non-empty ASCII string whose characters are literal: no ranges. Only runs of the same character from chars are collapsed. Other characters, and runs of characters not in chars, stay as they are. Case matters, and lines may be empty.

    For ["aaabbb", "abaa"] and chars = "a", the answer is "abbb\naba". The run aaa becomes a, but bbb stays because b is not in chars.

    Approach: skip a character that repeats the one just before it

    Walk through the line one character at a time and build the output. A character is dropped only when two things are true: it belongs to the squeeze set, and it is the same as the last character that was kept. Then the first character of every run is kept, and the repeats after it are skipped.

    Keeping track of the last kept character is enough, because a dropped character equals the kept one before it, so nothing is lost. The variable prev holds it. At the start of each line nothing came before, so prev starts as '\0', the null character, which isn't in a line of ordinary text.

    The membership test uses a Set<Character> built once from chars, so each check is constant on average.

    Here is "aaabbb" with chars = "a", one character at a time:

    a kept -> a
    a skipped
    a skipped
    b kept -> ab
    b kept -> abb
    b kept -> abbb
    

    The b characters are kept every time. They repeat each other, but b isn't in the set.

    Step by step

    1. Create squeeze, a Set<Character> set to a new HashSet, for the characters to squeeze.
    2. Loop over the positions of chars with i from 0 to chars.length() - 1.
    3. Add each character with squeeze.add(chars.charAt(i)).
    4. Create result, an empty list of strings for the squeezed lines.
    5. Loop over the lines with a for-each loop that names each element line.
    6. Create a fresh StringBuilder named sb for the characters this line keeps.
    7. Create prev as '\0', the last character that went into sb. It is reset for every line, so a run never continues across a line break.
    8. Loop over the positions of line with j from 0 to line.length() - 1.
    9. Read the character at position j into a char named ch.
    10. Test for a squeezable repeat: squeeze.contains(ch) && ch == prev. Both parts must hold.
    11. Skip it with continue. It jumps to the next character, so this one is never appended and prev stays as it is.
    12. Append ch to sb when the test failed.
    13. Set prev to ch, so the next character is compared with the last one kept.
    14. After the inner loop, add sb.toString() to result. A line can end up empty, and it stays in the output as an empty line.
    15. After the outer loop, return String.join("\n", result).

    The solution in Java

    class Solution {
        public String trSqueeze(List<String> lines, String chars) {
            Set<Character> squeeze = new HashSet<>();
            for (int i = 0; i < chars.length(); i++) {
                squeeze.add(chars.charAt(i));
            }
            List<String> result = new ArrayList<>();
            for (String line : lines) {
                StringBuilder sb = new StringBuilder();
                char prev = '\0';
                for (int j = 0; j < line.length(); j++) {
                    char ch = line.charAt(j);
                    if (squeeze.contains(ch) && ch == prev) {
                        continue;
                    }
                    sb.append(ch);
                    prev = ch;
                }
                result.add(sb.toString());
            }
            return String.join("\n", result);
        }
    }
    

    Details worth knowing:

    • char compares with ==. ch == prev compares two primitive characters, which is correct. The set holds Character objects, but squeeze.contains(ch) boxes the primitive for you.
    • continue versus break. continue ends only the current pass of the inner loop, so the next character is still processed. break would leave the loop and cut the line short.
    • The single quotes make a char. '\0' is one character, whereas "\0" would be a String.
    • Imports. List, ArrayList, Set and HashSet are in java.util.

    Complexity

    Time: O(m + t), where m is the length of chars and t is the total number of characters in all lines. Each character of the text costs one set lookup and one comparison.

    Space: O(m + t). The set holds at most m characters, and the builders and the result hold the squeezed text.

    Edge cases and common mistakes

    • Several characters in the set. ["aaabbb", "abaa"] with "ab" gives "ab\naba". Each run is squeezed on its own.
    • Squeezing spaces. ["a b c"] with a single space in chars gives "a b c".
    • Runs that aren't squeezed. ["aabb"] with "b" gives "aab": the two a characters stay, because a isn't in the set.
    • Letters separated by other letters. ["mississippi"] with "sp" gives "misisipi". The runs ss and pp shrink, but each letter that returns later is kept.
    • Case. ["aAaA"] with "a" gives "aAaA". A capital A is a different character, so there are no repeats.
    • Setting prev too early or too late. It must be updated after the check, from the character just handled. Updating it before the test would make every character look like a repeat of itself.
    • Empty lines. ["", "x"] with "x" gives "\nx".
    • Forgetting to reset prev. Declared outside the line loop, it would carry the last character of one line into the next.

    Testing

    • ["aaabbb", "abaa"] with "a" gives "abbb\naba".
    • ["aaabbb", "abaa"] with "ab" gives "ab\naba".
    • ["a b c"] with a single space gives "a b c".
    • ["mississippi"] with "sp" gives "misisipi".
    • ["", "x"] with "x" gives "\nx".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free