0

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?

1 Answer 1

1

O(3n) ~ O(2n) ~ O(n) so basically the worst-case complexity of these two are the same

Ref: Big O notation > Multiplication by a constant

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.