There is a key importance between the two methods. reverse()
mutates the Array
in place, so its time complexity has to be O(n)
since it needs to exchange the order of all elements.
However, on the other hand, if you check the return type of reversed()
, it is ReversedCollection<Array<Element>>
and the documentation clearly states that instead of returning a new Array
instance, the reversed()
method returns a wrapper type that simply contains the original array and provides access to its elements in reverse order. This wrapper type, ReversedCollection
can be created in constant time, hence the time complexity of reversed()
is O(1)
.
The example code you mention obviously has O(n)
time complexity, since word.reversed()
is traversed using a loop, however, the time complexity mentioned in the documentation simply relates to the function call, word.reversed()
, which is indeed O(1)
for the reasons mentioned above.