-1

At a last iOS Developer job interview I got a task that I didn't quite know how to do properly.

Task: Reverse an array of integers in place.

Inputs: arr (the array), and n - which is the number of elements in arr

Allocate as little memory as possible, and don't use Swift's object properties (so basically anything you access with a dot notation e.g .reverse(), .insert(at: etc. is not allowed)

mrkot
  • 107
  • 2
  • 8

1 Answers1

3

With tuples

func reverse(array: inout [Int], count: Int) {
    if count < 2 { return }
    var first = 0
    var last = count - 1
    while first < last {
        (array[first], array[last]) = (array[last], array[first])
        first += 1
        last -= 1
    }
}

Without tuples

func reverse(array: inout [Int], count: Int) {
    func swapAt(_ firstIndex: Int, _ secondIndex: Int) {
        let firstValue = array[firstIndex]
        array[firstIndex] = array[secondIndex]
        array[secondIndex] = firstValue
    }

    if count < 2 { return }
    var first = 0
    var last = count - 1
    while first < last {
        swapAt(first, last)
        first += 1
        last -= 1
    }
}
Damiaan Dufaux
  • 4,427
  • 1
  • 22
  • 33