Stop gninnipS My sdroW!
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.Codewars
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test"
1. if str.length < 5 then return str
2. split string words into array of strings
3. for each string in array
3.1. if string.length >= 5 split into array of charachters
3.2. reverse array of charachters
3.3 Join array of charachters to a string
4. return string joined from array of strings
Assuming that the
reverse function is running at linear time – O(n).
Array.join is linear – O(n),
Array.reverse also runs at linear – O(n) same about the
Array.split function, which gives us a linear – O(n) where n is the substring length (word.length).
Then we have both
Array.split which are also running at linear, and they are both running on the array created for each element on the string.
That gives us O(num of words * num of words chars).
Let’s try to improve it.
This algorithm still runs at the same time, but at least it drops a few constants.