4 ms·
possibly because it's much harder (maybe impossible?) to do in languages that don't have native tuples, which appear to be the ask. The input string is quoted,
by pcthrowaway 6y ago
possibly because it's much harder (maybe impossible?) to do in languages that don't have native tuples, which appear to be the ask.
The input string is quoted, so the output appears to be an array (not a string type).
My stab at it in Javascript resulted in:
function collapse(a) {
collapsedArray = [];
for (let i=0; i<a.length; i++) {
let count = 1;
let currentchar = a[i];
while (i+1 < a.length && a[i+1] == currentchar) {
i++;
count++;
}
collapsedArray.push([a[i], count]);
}
return (collapsedArray);
}
console.log(JSON.stringify(collapse("aabbcdde")));
This outputs `[["a",2],["b",2],["c",1],["d",2],["e",1]]`. Without native tuples in Javascript (or JSON), I could construct a string which replaces the inner brackets with parens, but that would be pretty contrived, as the output requested isn't quoted.
- Supermancho 6y ago> the output requested isn't quoted. Input: "aaaabbbcca" Output: [("a", 4), ("b", 3), ("c", 2), ("a", 1)] The input and output is explicit. The interpretation is a talking point. Serialization into parens is not native for most? scripting languages. Creating a string would probably be most efficient for the output format, for sure. It's important to remember that interview questions are not just about the algorithm (for which this is trivial) but the requirements. Asking if the double quotes are representing strings (and what kind of strings for some languages) is part of the natural back-and-forth of an interview.