X
X
Xenia2018-05-31 16:39:22
JavaScript
Xenia, 2018-05-31 16:39:22

What is the complexity of the algorithm?

Help plz estimate the complexity of the algorithm (expands letters in words without changing the order of words):

const reverseWords = (str) => {
  const wordsArr = str.split(' ');
  const reversedArr = wordsArr.map((word) => {
    let newWord = '';
    for (let i = word.length - 1; i >= 0; i--) {
      newWord += word[i];
    }
    return newWord;
  });
  const reversedStr = reversedArr.join(' ');
  return reversedStr;
};

module.exports = reverseWords;
// O(n)?

According to my feelings, O (n) comes out.
I'm right? Or O(n*m)?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Olohtonov, 2018-05-31
@TGNC

O(n), only 3 passes through the string: split, reverse, join.

A
Alexander Trakhimenok, 2018-05-31
@astec

In this implementation, most likely at least O(4n)
Split, reverse, join + concatenation (newWord+=)

S
string15, 2018-06-14
@string15

I guess O(5n)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question