How to perform reversing of all words in a sentence.
Example
let str = \"Hello playground\"
Result should be like \"olleH dnuorg
Here's the typical functional programming approach (also posted by @Saranjith)
let result = str
.components(separatedBy: " ")
.map { $0.reversed() }
.joined()
First of all lets define
n
: the number of characters in the input stringk
: the number of words in the input string (of course k<=n) Now lets look at the time complexity of each piece of our code
.components(separatedBy: " ")
This instructions need to go through the entire string so O(n)
.map { $0.reversed() }
Here each word is reversed. So if we have k
words we have a time complexity of
O(m0) + O(m1) + ... + O(mk-1)
where mi
is the length of the i-th
word.
However the sum of the length of all the words is <= n so we can say that
O(m0) + O(m1) + ... + O(mk-1) <= O(n)
.joined()
Finally we have k
words which need to be joined togheter. This can be done in O(k)
that, again, is <= O(n)
.
Wrap up
let result = str
.components(separatedBy: " ") // O(n)
.map { $0.reversed() } // O(m0) + O(m1) + ... + O(mk-1) <= O(n)
.joined() // O(k) <= O(n)
Time complexity = O(n) + O(n) + O(n) = O(n)