Start learning free

LESSON 28 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in Python: Squeezing 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:

def trSqueeze(self, lines: List[str], chars: str) -> str:

Example:

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

Output: "abbb\naba"

When printed:
abbb
aba

Build a set of squeeze characters. Walk each line tracking the previous emitted character. Skip the current char only if it's in the squeeze set AND it equals prev.

prev = ''
for ch in line:
    if ch in squeeze and ch == prev:
        continue
    out.append(ch)
    prev = ch


The full solution:
class Solution:
    def trSqueeze(self, lines, chars):
        squeeze = set(chars)
        result = []
        for line in lines:
            out = []
            prev = ''
            for ch in line:
                if ch in squeeze and ch == prev:
                    continue
                out.append(ch)
                prev = ch
            result.append(''.join(out))
        return "\n".join(result)

STEP 1 OF 12
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Python, explained

    Problem overview

    The fourth version of the tr tool mimics tr -s. The method trSqueeze receives a list of lines and a string chars. In every line, a run of the same character that appears in chars collapses to a single occurrence. Other characters, and runs of characters not in chars, stay as they are. The lines are returned joined by "\n".

    For ["aaabbb", "abaa"] and chars = "a", the result is "abbb\naba": the run of as becomes one a, while bbb is untouched, because b is not in chars. The characters are literal, case matters, and lines may be empty.

    Approach: skip a character that repeats the last kept one

    The earlier versions had a built-in string method to lean on. Here there is none, so the loop walks each line character by character and builds the output itself. It remembers the last character that was kept, prev. A character is skipped when two things are both true: it is one of the squeeze characters, and it equals prev. Anything else is kept.

    The squeeze characters go into a set. A set answers "is this character one to squeeze?" in constant time, and set(chars) takes each character of the string as one member.

    The state for one line is tiny: the list out and the single character prev. For "aaabbb" with chars = "a", the first a is kept and the next two equal prev and are skipped. Then each b is kept, because b is not in the set, so "aaabbb" becomes "abbb". A line made of only as, such as "aaaa", collapses to a single "a", not to an empty string.

    Step by step

    1. Create squeeze = set(chars).
    2. Create an empty list result for the finished lines.
    3. Write the outer for loop, line taking each line of lines.
    4. Inside it, create a fresh empty list out for the characters this line keeps. It must be new for each line, or the lines would mix.
    5. Also inside it, create prev = ''. At the start of a line nothing came before, so it starts empty.
    6. Write an inner for loop, ch taking each character of line.
    7. Inside, write if ch in squeeze and ch == prev: and, in its body, continue. This jumps to the next character, so this one is never added.
    8. After the if, still in the inner loop, append ch to out and set prev = ch. The first character of a run is kept; only the repeats are dropped.
    9. After the inner loop, append ''.join(out) to result. This runs once per line, so it sits outside the inner loop.
    10. After the outer loop, return "\n".join(result).

    The solution in Python

    class Solution:
        def trSqueeze(self, lines, chars):
            squeeze = set(chars)
            result = []
            for line in lines:
                out = []
                prev = ''
                for ch in line:
                    if ch in squeeze and ch == prev:
                        continue
                    out.append(ch)
                    prev = ch
                result.append(''.join(out))
            return "\n".join(result)
    

    Some details:

    • Looping over a string hands out one character at a time, each as a string of length 1.
    • prev holds the last character kept. Because skipped characters equal prev anyway, it is also the previous character of the original line.
    • Starting prev as '' is safe, because no real character equals the empty string, so the first character of a line is never skipped.
    • Two join calls with different separators do two different jobs: ''.join(out) builds one line from its characters, and "\n".join(result) builds the answer from the lines.

    Complexity

    Every character is visited once with constant work: a set lookup, a comparison and an append. The total time is linear in the number of characters in all lines, plus the size of chars to build the set. The lists out and result need extra space of the same order.

    Edge cases and common mistakes

    linescharsresult
    ["aaabbb", "abaa"]"a""abbb\naba"
    ["aaabbb"]"ab""ab"
    ["aabbaa"]"a""abba"
    ["", " x y"]" ""\n x y"
    ["aaabbb"]"c""aaabbb"
    • In the third row the two runs of a are separate, with bb between them, and each collapses on its own.
    • In the fourth row the empty line stays empty and keeps its place, and each run of spaces becomes one space.
    • Only runs of the same character collapse. In the second row, a and b are both squeezed, but aaabbb becomes ab because each run collapses separately; ab is not treated as one run.
    • The continue could be replaced by putting the append and the update of prev in an else branch. Both forms do the same thing; continue keeps the two lines that are always executed for a kept character at the same indent as the loop body.
    • Forgetting to reset out and prev for each line carries state from one line into the next.
    • Updating prev only when the character is in squeeze is a bug. With chars = "a", the line "aba" then becomes "ab": the b doesn't update prev, so the last a is compared with the first one and wrongly skipped. Set prev for every character that is kept, so that only truly adjacent repeats are dropped.
    • Squeezing is not the same as removing duplicates: with chars = "ab", the line "aabbab" becomes "abab", because the a and b that alternate are not repeats of each other.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free