Chapter 7 challenge 4

Solution from the book uses insert method to reverse the array which is add at position 0 then shift all the elements to the right 1 time which is O(n).

    func reversed(_ array: [Int]) -> [Int] {
  var newArray: [Int] = []
  for item in array {
    newArray.insert(item, at: 0)
  }
  return newArray
}

Isn’t it better to use append method instead ?

    func kreversed(_ array: [Int]) -> [Int] {
  var newArray: [Int] = []
    
    let position = array.count - 1
    
    for index in array{
        newArray.append(array[position - index])
    
    }
  
    return newArray
}

little improved version

func reversed(_ array: [Int]) -> [Int]{
var newArray:[Int] = []

var counter = array.endIndex - 1

for _ in array{
    newArray.append(array[counter])
    counter -= 1
}

return newArray

}

Hi @surepic, thank you for sharing an alternative solution with the community and welcome to the forum!

Hi! Thanks for sharing surepic. Yes, your version is more efficient!

You can it even a little faster by calling

newArray.reserveCapacity(array.count)

That way append won’t need to worry about doing the allocations. Depending on the size it might have to do multiple reallocations and copies if it doesn’t know the size.

By the way, if you cheat and use the standard library (which you should in practice!) you can do it like so

func reversed(_ array: [Int]) -> [Int] { Array(array.reversed())  }

The method reversed() is O(1) and returns a lazy ReversedCollection<Array<Int>>. Then you initialize that with an array that iterates through the reverse collection (as you have done) and constructs the Array in one go. It has the same good performance characteristics as your hand rolled loop. :smile:

Glad you are thinking about performance!

But this way array.count is being called which should start counting again.
As i understood with endindex-1 will be faster cos its hashed.

May be im wrong but understood so far.

count is O(1) for RandomAccessCollection. It is actually implemented as endIndex - startIndex because collections might not start from zero, as is the case with ArraySlice.

Good to know that! Thanks

This topic was automatically closed after 166 days. New replies are no longer allowed.