Start learning free

LESSON 28 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in C#: 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<char>. 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) {
        HashSet<char> squeeze = new HashSet<char>();
        for (int i = 0; i < chars.Length; i++) {
            squeeze.Add(chars[i]);
        }
        List<string> result = new List<string>();
        foreach (string line in lines) {
            StringBuilder sb = new StringBuilder();
            char prev = '\0';
            for (int j = 0; j < line.Length; j++) {
                char ch = line[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

    C# · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in C#, explained

    Problem overview

    This version of TrSqueeze imitates tr -s. It takes a List<string> of lines and a non-empty string chars. In each line, every run of the same character that appears in chars collapses to one occurrence. All other characters, and runs of characters that are not in chars, stay as they are. The lines are returned joined with "\n". Case matters, and lines may be empty.

    For ["aaabbb", "abaa"] with chars = "a", the result is "abbb\naba". The three as become one, and the bs are not in chars, so they stay. In "abaa" the first a is alone and the last two collapse to one.

    Approach: skip a character that repeats the one just kept

    A character is dropped when two things are both true: it is one of the characters to squeeze, and it is equal to the character kept just before it. Everything else is appended. So the method needs two things for each line:

    • a HashSet<char> of the squeezable characters, built once;
    • a variable prev for the last character that went into the output.

    Comparing with the previous kept character is what limits the squeeze to runs of the same character. In "aabb" with chars = "ab", the second a equals prev and is skipped. The first b differs from prev (a), so it is kept, and the second b is then skipped. The result is "ab", not "a".

    Trace "aaabbb" with chars = "a". The first a is in the set, but prev is '\0', so it is kept and prev becomes a. The second and third a are in the set and equal prev, so both are skipped. Each b is not in the set, so the first part of the test is false, and all three are kept. The builder holds "abbb".

    Step by step

    1. Create squeeze, an empty HashSet<char>.
    2. Loop over the positions of chars with i.
    3. Add chars[i] to the set.
    4. Create result, an empty List<string>.
    5. Write a foreach loop over lines with the variable line.
    6. Create a StringBuilder sb for this line.
    7. Create char prev = '\0', the null character. At the start of a line nothing has been kept, so prev starts as a value that is not expected in a line.
    8. Loop over the characters of line with j.
    9. Read the character at position j into char ch.
    10. Test squeeze.Contains(ch) && ch == prev. The character is skipped only when both parts hold.
    11. Write continue inside the if. It jumps to the next character, so this one is never appended.
    12. Append ch to sb after the if. The first character of a run is kept, and only the repeats after it are dropped.
    13. Set prev = ch. prev always holds the last kept character, so the next character is compared with it.
    14. After the inner loop, add sb.ToString() to result.
    15. After the outer loop, return string.Join("\n", result).

    The solution in C#

    class Solution {
        public string TrSqueeze(List<string> lines, string chars) {
            HashSet<char> squeeze = new HashSet<char>();
            for (int i = 0; i < chars.Length; i++) {
                squeeze.Add(chars[i]);
            }
            List<string> result = new List<string>();
            foreach (string line in lines) {
                StringBuilder sb = new StringBuilder();
                char prev = '\0';
                for (int j = 0; j < line.Length; j++) {
                    char ch = line[j];
                    if (squeeze.Contains(ch) && ch == prev) {
                        continue;
                    }
                    sb.Append(ch);
                    prev = ch;
                }
                result.Add(sb.ToString());
            }
            return string.Join("\n", result);
        }
    }
    

    The C# details:

    • '\0' is a char literal for the character with code 0. It is a placeholder here, since ordinary text doesn't contain it.
    • && short-circuits. If squeeze.Contains(ch) is false, the comparison with prev isn't evaluated, and the character is appended.
    • continue applies to the innermost loop. Here that is the loop over j, so the next character of the same line is processed. The outer foreach is unaffected.
    • prev is declared inside the foreach, so every line starts with a fresh '\0'. A character at the start of one line can't be treated as a repeat of the end of the previous line.
    • Chars are values. ch == prev compares the two characters by code, so 'a' and 'A' are not equal.

    The method never looks ahead and never needs to remember more than one character. That is what keeps the work to a single pass over each line: the decision for each character depends only on the character itself and on the last one kept.

    Complexity

    Let k be the length of chars and L the total number of characters in all lines. Time: O(k + L), since each character costs one set lookup and one comparison. Space: O(k + L) for the set, the builders and the output.

    Edge cases and common mistakes

    • Different characters in a row. ["aabbcc"] with "ab" gives "abcc". The cs are not in chars, so they stay doubled.
    • Alternating characters. ["abab"] with "ab" stays "abab", because no character repeats the one right before it.
    • Case. ["aAaa"] with "ab" gives "aAa": only the last two lowercase as are a run.
    • Spaces. chars may be a space. ["", " x y"] with " " gives "\n x y": the empty line stays, and each run of spaces becomes one.
    • Several squeezed characters. ["mississippi"] with "sp" gives "misisipi".
    • Checking only ch == prev. Without the set test, every repeated character would collapse, including the bs in "aaabbb", which the lesson keeps.
    • Checking only the set. Without the prev test, every squeezable character would be dropped, which is deletion, not squeezing: "abaa" with "a" would become "b" instead of "aba".

    Testing

    • ["aaabbb", "abaa"], "a" gives "abbb\naba".
    • ["aabbcc"], "ab" gives "abcc".
    • ["abab"], "ab" gives "abab".
    • ["mississippi"], "sp" gives "misisipi".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free