4

I have read apple developer document:

Array.reverse()

Array.reversed()

the fist article points out: Complexity: O(n), where n is the number of elements in the collection.

the second article points out: Complexity: O(1), and without any reason.

Is that just a little mistake or other reason?

Because second article takes a example for

let word = "Backwards"
for char in word.reversed() {
    print(char, terminator: "")
}
// Prints "sdrawkcaB"

I think O(n) is correct answer. right?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
nine9
  • 147
  • 1
  • 2
  • 8
  • 1
    Related: [Why does the reverse() function in the Swift standard library return ReverseRandomAccessCollection? Ask Question](https://stackoverflow.com/q/34558390/1187415). – Martin R Jul 16 '18 at 15:01

2 Answers2

20

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • is it the same principle of Circular linked list? – Moayad Al kouz Jul 16 '18 at 14:13
  • @MoayadAlkouz there's no such built-in type in Swift, so I can't really refer to that, since it's rather an implementation detail than a principle of a data structure in the case of `reverse()` and `reversed()` – Dávid Pásztor Jul 16 '18 at 14:15
2

Is that just a little mistake or other reason?

I think O(n) is correct answer. right?

No, reverse() actually takes O(n) and reversed() O(1).

The example is a little bit confusing, but you should better separate it into two parts.

let word = Array("Backwards")
let reversedWord = word.reversed() //<- O(1) is the complexity of this operation.
for char in reversedWord { //<- This for-in loop, of course is O(n)
    print(char, terminator: "")
}
// Prints "sdrawkcaB"

In case of reverse():

var word = Array("Backwards")
word.reverse() //<- This operation takes O(n)
for char in word {
    print(char, terminator: "")
}
// Prints "sdrawkcaB"
OOPer
  • 47,149
  • 6
  • 107
  • 142