Start learning free

LESSON 28 OF 71 · PROJECTS: COMMAND-LINE TOOLS

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

func trSqueeze(_ lines: [String], _ chars: String) -> String

Example:

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

Output: "abbb\naba"

When printed:
abbb
aba

Put each char of chars into a Set<Character>. Walk each line tracking prev (the last char you kept); skip the current char only if it's in the set AND equals prev.

The full solution:
class Solution {
    func trSqueeze(_ lines: [String], _ chars: String) -> String {
        var squeeze = Set<Character>()
        for ch in chars {
            squeeze.insert(ch)
        }
        var result = [String]()
        for line in lines {
            var sb = ""
            var prev: Character = "\0"
            for ch in line {
                if squeeze.contains(ch) && ch == prev {
                    continue
                }
                sb.append(ch)
                prev = ch
            }
            result.append(sb)
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 14
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Swift, explained

    Problem overview

    The fourth version of tr behaves like tr -s. trSqueeze(_ lines: [String], _ chars: String) -> String collapses each run of the same character into a single character, but only for characters that appear in chars. Everything else is unchanged, and the lines are joined with "\n". chars is non-empty ASCII, taken literally, and case matters.

    For ["aaabbb", "abaa"] and "a" the result is "abbb\naba". The run of a at the start of the first line shrinks to one a, but the b run is not in chars, so it stays whole.

    Approach: skip a character that repeats the one just kept

    A run is squeezed by keeping its first character and skipping the rest. So while scanning a line, compare each character with the last one you kept, prev. A character is skipped only when both conditions hold: it is in chars, and it equals prev. Otherwise it is appended to the output and becomes the new prev.

    The test for membership uses a Set<Character>, as the previous version did for deletion. What changes is the extra memory of the last kept character.

    Here is the idea on "aabbaa" with chars = "a". The second a repeats the first, so it goes. The two b characters stay, because b is not in the set. The last two a characters are a new run, so one goes. The result is "abba".

    Tracing "aabbaa" with chars = "a" character by character gives:

    CharacterDecisionOutput so far
    akepta
    askippeda
    bkeptab
    bkeptabb
    akeptabba
    askippedabba

    The second b is kept even though it equals prev, because b is not in the set. The fifth character is kept because the last kept character was b, so a new run of a begins.

    Each line starts over with a fresh sb and a fresh prev, so a run never continues across a line break. With ["a", "a"] and "a" the answer is "a\na": two lines, each holding one a, not one a in total. The same holds when a line ends and the next one begins with the same character: ["xaa", "aax"] gives "xa\nax".

    Step by step

    1. Create squeeze as an empty Set<Character> with var.
    2. Loop over each ch in chars.
    3. Insert ch into squeeze. Duplicates in chars are absorbed by the set.
    4. Create result, an empty [String].
    5. Loop over each line in lines.
    6. Create sb, an empty string, to hold the characters this line keeps.
    7. Create prev as a Character set to "\0", the null character. At the start of a line nothing has been kept, so prev starts as a character that does not occur in the lines.
    8. Loop over each ch in line.
    9. Test squeeze.contains(ch) && ch == prev. Both must be true to skip a character.
    10. Write continue inside that test. It jumps to the next character, so this one is never appended.
    11. After the test, append ch to sb. The first character of a run always gets here.
    12. Set prev = ch. prev is always the last character kept.
    13. Append sb to result after the inner loop. A line may come out empty, and it still goes in.
    14. Return the joined lines after the outer loop.

    The solution in Swift

    class Solution {
        func trSqueeze(_ lines: [String], _ chars: String) -> String {
            var squeeze = Set<Character>()
            for ch in chars {
                squeeze.insert(ch)
            }
            var result = [String]()
            for line in lines {
                var sb = ""
                var prev: Character = "\0"
                for ch in line {
                    if squeeze.contains(ch) && ch == prev {
                        continue
                    }
                    sb.append(ch)
                    prev = ch
                }
                result.append(sb)
            }
            return result.joined(separator: "\n")
        }
    }
    

    Details that matter:

    • A Character literal. "\0" is a double-quoted literal, but the annotation : Character makes it a single character instead of a string. Without the annotation, Swift would infer String, and ch == prev would no longer compile.
    • Why a sentinel. The null character stands for "nothing kept yet". Since the lines hold ordinary text, no real character equals it, so the first character of every line is kept.
    • continue. It ends the current pass of the inner loop only. The outer loop and the remaining characters of the line are unaffected.
    • && short-circuits. If the first test, squeeze.contains(ch), is false, Swift doesn't evaluate the second.
    • prev follows kept characters. The continue jumps over prev = ch, so prev changes only when a character is kept. A skipped character equals prev anyway, so nothing is lost.

    Complexity

    Time: O(k + m), for k characters in chars and m characters across all lines: each line character costs one set lookup, one comparison and at most one append. Space: O(k + m) for the set and the output.

    Edge cases and common mistakes

    • Only runs of the same character collapse. ["ababab"] with "ab" returns "ababab", because no character repeats directly after itself.
    • Characters outside chars are never squeezed. ["aabbaa"] with "a" returns "abba": the bb stays.
    • Several characters at once. ["aabbcc"] with "ab" returns "abcc". The a and b runs shrink; the c run does not.
    • Spaces. ["a b c"] with a single space as chars returns "a b c".
    • Case. ["aAaA", "AAaa"] with "a" returns "aAaA\nAAa". In the second line the two uppercase letters are not in the set, and the lowercase pair squeezes to one.
    • Empty lines. ["", "x"] with "x" returns "\nx".
    • Skipping with the wrong test. Testing only ch == prev would squeeze every run, including bbb in the example, which should stay.

    Testing

    • ["aaabbb", "abaa"], "a" gives "abbb\naba".
    • ["aabbaa"], "a" gives "abba".
    • ["aabbcc"], "ab" gives "abcc".
    • ["a b c"], " " gives "a b c".
    • ["aAaA", "AAaa"], "a" gives "aAaA\nAAa".
    • ["", "x"], "x" gives "\nx".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free