Problem overview
This version of the tr tool squeezes repeats, like tr -s. The method trSqueeze(lines, chars) receives an array of lines and a non-empty string chars. In each line, a run of the same character that is listed in chars collapses into one occurrence. The result is the lines joined by \n.
Only runs of a character from chars are touched. Runs of any other character stay as they are. Case matters, and lines may be empty.
For ["aaabbb", "abaa"] with chars = "a", the result is "abbb\naba". The "aaa" becomes "a", the "bbb" is not in chars, and in "abaa" only the final pair of as is a run.
Approach: skip a character that repeats the last kept one
A character should be dropped when two things are true: it is in chars, and it equals the character just before it. So the loop only has to remember the previous character of the line.
The lesson stores that memory in prev, the last character that went into the output. For each character ch: if chars contains it and ch === prev, skip it with continue. Otherwise append it to the output and make it the new prev. The first character of a run always passes, because prev is different, and the repeats after it are skipped.
At the start of each line prev is the empty string, which no one-character string equals. That way the first character of a line is never mistaken for a repeat of the previous line's last character.
Step by step
- Create the set.
let squeeze = new Set(chars)makes each character ofcharsa member, sohasanswers "is this one to squeeze?" quickly. - Create
result, an empty array for the squeezed lines. - Loop over the lines with
i. - Create
out, an empty string holding the characters this line keeps. - Create
prevas an empty string. It remembers the last character added toout. - Loop over the characters of
lines[i]withj. - Take the character at position
jintoch. - Test for a repeat:
squeeze.has(ch) && ch === prev. Both parts must be true. - Skip it with
continue, which jumps to the next character, so this one is never added. - Append
chtooutafter theif. - Update
prevtoch, so the next character is compared with the latest kept one. - Push
outontoresultafter the inner loop. A line can be empty and still gets pushed. - Return
result.join("\n")after the outer loop.
Tracing the example
For the line "aaabbb" with chars = "a", the inner loop proceeds as follows:
| ch | action | out afterwards | prev afterwards |
|---|---|---|---|
| "a" | keep | "a" | "a" |
| "a" | skip | "a" | "a" |
| "a" | skip | "a" | "a" |
| "b" | keep | "ab" | "b" |
| "b" | keep | "abb" | "b" |
| "b" | keep | "abbb" | "b" |
The repeated "b"s equal prev, but "b" is not in squeeze, so the first half of the test is false and they are kept. The line becomes "abbb".
The second line, "abaa", shows why prev must be the last character kept. The first "a" is kept, the "b" is kept and becomes prev, so the next "a" is no longer a repeat and is kept too. Only the last "a" equals prev and is skipped, which gives "aba". The final join then returns "abbb\naba".
The solution in JavaScript
class Solution {
trSqueeze(lines, chars) {
let squeeze = new Set(chars);
let result = [];
for (let i = 0; i < lines.length; i++) {
let out = "";
let prev = "";
for (let j = 0; j < lines[i].length; j++) {
let ch = lines[i][j];
if (squeeze.has(ch) && ch === prev) {
continue;
}
out += ch;
prev = ch;
}
result.push(out);
}
return result.join("\n");
}
}
The JavaScript details:
continueaffects the innermost loop. It ends the current pass of thejloop and moves on to the next character. Theiloop is not affected.&&short-circuits. Ifsqueeze.has(ch)is false,ch === previs not evaluated, and the character is kept.===on strings compares text. Two one-character strings are equal when they contain the same character, so"a" === "a"is true.- Skipped characters don't need to update
prev. A skipped character equalsprev, so updating it would change nothing. - Strings are immutable.
out += chcreates a new string each time. This is fine at these sizes.
Complexity
Let k be the length of chars and N the total number of characters in all lines.
Time: O(k + N). Building the set takes k steps, and each character costs one set lookup, one comparison and at most one append.
Space: O(k + N) for the set and for the output, which is never longer than the input.
Edge cases and common mistakes
- Only listed characters collapse.
["aabb"]with"x"gives"aabb": neither letter is inchars. - Several characters.
["aaabbb"]with"ab"gives"ab", and["a b c"]with a single space gives"a b c". - Alternating characters are not runs.
["abab"]with"ab"stays"abab", since no letter is next to an equal one. - Case matters.
["aAaA"]with"a"stays"aAaA", because"A"and"a"are different characters. - Empty lines.
["", "ee"]with"e"gives"\ne". The empty line stays empty. - Not resetting
prevfor each line. A line starting with a listed character could then lose it when the previous line ended with the same one. Declaringprevinside the outer loop prevents this. - Squeezing every repeat. Dropping any character equal to the previous one, listed or not, would also shorten
"bbb", which must stay as it is.
Testing
["aaabbb", "abaa"],"a"gives"abbb\naba".["aaabbb"],"ab"gives"ab".["a b c"]," "gives"a b c".["abab"],"ab"gives"abab".["", "ee"],"e"gives"\ne".
