2
function reverseString(str) {
  let newStr = ''
  for (let i = (str.length - 1); i >= 0; i--) {
    newStr += str[i]
  }

  return newStr
}

// This algorithm is faster
function reverseString2(str) {
  str = str.split('')
  let left = 0
  let right = str.length - 1
  while (left < right) {
    const tmp = str[left]
    str[left] = str[right]
    str[right] = tmp
    left++
    right--
  }
  return str.join('')
}

Why is reverseString2 faster than reverseString if the function does more processing, converting the string to an array and then concatenating the whole array? The advantage is that the main algorithm is O(n/2) but the rest is O(n). Why does that happen?

The results are the following:
str size: 20000000
reverseString: 4022.294ms
reverseString2: 1329.758ms

Thanks in advance.

Boann
  • 48,794
  • 16
  • 117
  • 146
Eladiorocha
  • 146
  • 1
  • 6
  • 2
    In ```reverseString```, each append operation requires extra memory for the string, whereas in the second approach, we're just switching the values stored at each pair of index. Concatenating the list is also fast enough since it is a linear data structure – Abhinav Mathur Apr 17 '21 at 04:40

1 Answers1

0

In the first function reverseString(), what is happening is that the loop is running 'n' times. Here 'n' is meant to signify the length of the string. You can see that you are executing the loop n times to get the reversed string. So the total time taken by this function depends on the value of 'n'.

In the second function reverseString2(), the while loop is running only n/2 times. You can understand this when you look at the left and the right variable. For one execution of the loop, the left variable is increasing by 1 and the right variable is decreasing by 1. So you are doing 2 updation at once. So for a n-length string, it only executes for n/2 times.

Although there are much more statements in the second function, but they are being executed much less time than those statements in the first function. Hence the function reverseString2() is faster.

IMPERIO
  • 62
  • 3