Problem overview
The fourth version of the tr project imitates tr -s. The method trSqueeze(lines: string[], chars: string) collapses every run of the same character, when that character is in chars, into a single occurrence. All other characters stay as they are, including runs of characters that are not in chars. The lines are returned joined by \n.
chars is non-empty ASCII, taken literally. Case matters, and lines may be empty. For ["aaabbb", "abaa"] with chars = "a" the result is "abbb\naba": the run of a in the first line shrinks to one, the bbb stays, and the two trailing as of the second line become one.
Approach: skip a character that repeats the one just kept
A repeat means "the same as the character right before it". So while building the output line, the code remembers the last character it added, in prev. A new character is dropped only when both things are true: it is in the set of characters to squeeze, and it equals prev. Everything else is added.
The two conditions are both needed. Without the set test, every repeat would be squeezed and "bbb" would shrink even though b is not in chars. Without the prev test, every character from the set would be dropped, not only the repeats. Only runs of the same character count: with chars = "ab", "aabbaa" becomes "aba", because a and b are each squeezed within their own runs, and the three runs stay as three characters.
The first character of a run always passes, since prev holds something else at that moment. At the start of each line prev is the empty string, which can't equal any character, so the first character of a line is always kept.
Why compare with the last character kept rather than the last character read? Here the two are always equal, because the only characters dropped are repeats of prev. If a character is dropped, it equals prev, so prev would not change anyway. Keeping a single variable that always holds the last character of out makes the rule easy to state: a character is dropped when it would repeat the end of the output.
Step by step
- Create the set of characters to squeeze:
let squeeze: Set<string> = new Set(chars). - Create
result, an emptystring[]. - Loop over the lines with
i. - Create
out, an empty string for the squeezed line. - Create
prev, also an empty string. Nothing came before the line, so it starts as a value that no character equals. - Loop over the characters of the line with
j. - Read the character into
ch. - Test for a repeat:
squeeze.has(ch) && ch === prev. - Skip it with
continue, which jumps to the next character, so this one is never added. - Append
chtoout. Only the first character of each run, and every unsqueezed character, reaches this line. - Update
prevtoch. It is always the last character kept. - Push
outontoresultafter the inner loop. An emptyoutis kept as an empty line. - Return
result.join("\n")after the outer loop.
The solution in TypeScript
class Solution {
trSqueeze(lines: string[], chars: string): string {
let squeeze: Set<string> = new Set(chars);
let result: string[] = [];
for (let i = 0; i < lines.length; i++) {
let out: string = "";
let prev: string = "";
for (let j = 0; j < lines[i].length; j++) {
let ch: string = lines[i][j];
if (squeeze.has(ch) && ch === prev) {
continue;
}
out += ch;
prev = ch;
}
result.push(out);
}
return result.join("\n");
}
}
Language details
continueends the current pass of the innermost loop and moves on to the nextj. It skips bothout += chandprev = ch. Skipping the update ofprevis harmless here, becauseprevalready equalsch.&&short-circuits: ifsqueeze.has(ch)is false, the comparison withprevis never evaluated.===compares two strings by content.- The annotations
Set<string>and: stringare checked by the compiler and erased when it produces JavaScript.
Complexity
Every character of every line is visited once, with an average O(1) set lookup, so the time is O(k + N) for k characters in chars and N characters in all the lines. The set uses O(k) space and the output O(N).
Edge cases and common mistakes
- Squeezing characters outside the set.
["bbb", "", "aaaa"]with"a"gives"bbb\n\na": thebs stay, the empty line stays, and the fouras become one. - Runs of different set characters.
["aabbaa"]with"ab"gives"aba", not"a": each run shrinks, and the runs are kept. - Spaces as squeeze characters.
["aXXa b"]with"a "gives"aXXa b": the double space shrinks, while theXXdoes not becauseXis not in the set. - Mutating the input. The method builds new strings and never changes
lines. - Case.
["aAaa"]with"a"gives"aAa". The capital A is a different character, so it breaks the run, and only the finalaais squeezed. - A line made only of squeezed characters. A line
"aaaa"with"a"becomes"a", not an empty line: the first character of the run is always kept. - Forgetting to reset
prev. Ifprevwere declared outside the outer loop, a line starting with the character that ended the previous line would lose its first character.
Testing
| Input | Result |
|---|---|
["aaabbb", "abaa"], "a" | "abbb\naba" |
["aabbaa"], "ab" | "aba" |
["aXXa b"], "a " | "aXXa b" |
["bbb", "", "aaaa"], "a" | "bbb\n\na" |
["aAaa"], "a" | "aAa" |
