Let's say that we're comparing two strings, that have a special character that causes something unusual to occur — in this case, the # character deletes the previous character.
Here's one solution that builds out strings and then compares them, using the string methods slice and concat:
const checkSame = (a, b) => {
let one = ''
for(let i = 0; i < a.length; i++){
if(a[i] === '#'){
one.slice(0, -1)
} else {
one.concat(a[i]);
}
}
let two = ''
for(let i = 0; i < b.length; i++){
if(b[i] === '#'){
one.slice(0, -1)
} else {
one.concat(b[i]);
}
}
return one === two
};
Here's another solution that uses arrays, and their methods push and pop:
export const compareTwoStrings2 = (a, b) => {
let one = [];
for (let i = 0; i < a.length; i++) {
if (a[i] === "#") {
one.pop();
} else {
one.push(a[i]);
}
}
let two = [];
for (let i = 0; i < b.length; i++) {
if (b[i] === "#") {
two.pop();
} else {
two.push(b[i]);
}
}
for(let i = 0; i < one.length; i++){
if(one[i] !== two[i]) return false;
}
return true;
};
The second solution uses an additional loop which makes me think that if given a string of n characters it would take O(3n) time (worst case), and the first would only take O(2n) time.
Is this correct? Is concatenating and slicing off a string more efficient than using arrays? Or does the final comparison of the two strings also take n time as the strings grow in length?