Home > Back-end >  Reverse Array Queries
Reverse Array Queries

Time:05-15

For a given array of integers, perform operations on the array. Return the resulting array after all operations have been applied in the order given. Each operation contains two indices. Reverse the subarray between those zero-based indices, inclusive.

1: arr is : [1, 2, 3] 1: operations is : [[0, 2], [1, 2], [0, 2]]

2: arr is : [640, 26, 276, 224, 737, 677, 893, 87, 422, 30] 2: operations is : [[0, 9], [2, 2], [5, 5], [1, 6], [5, 6], [5, 9], [0, 8], [6, 7], [1, 9], [3, 3]]

Here is what I have tried but does not seem to work

func performOperations(arr: [Int], operations: [[Int]]) -> [Int] {
// Write your code here
var arr = arr
var operations = operations
print("arr is : \(arr)")
print("operations is : \(operations)")
var v1 = 0
var v2 = 0
var count = 0
for (i, v) in operations.enumerated() {
    v1 = i
    for j in v {
        v2 = j
        if v1 > v2 {
            v2 = i
            v1 = j
        }
        
        // arr[v1] = arr[v2]
        // arr[v2] = arr[v1]
        
    }
    count = v2 - v1   1
}

for offset in 0..<count/2 {
    let f = v1   offset
    let s = v2 - offset
    var o = arr[f]
    var o2 = arr[s]
    arr[s] = o
    arr[f] = o2
    
}
return arr

}

1: enter image description here 2: enter image description here

CodePudding user response:

One solution is to divide the array in 3 parts for each operation, what is before the first index of the operation, what is after the second index and what is between and then merge the 3 parts once the middle one has been reversed.

func performOperations(array: [Int], operations: [[Int]]) -> [Int] {
    var result = array

    for op in operations {
        let reversed = Array(result[op[0]...op[1]].reversed())
        let prefix = result[result.startIndex..<op[0]]
        let suffix = result[op[1]   1..<result.endIndex]
        result = prefix   reversed   suffix
    }
    return result
}

CodePudding user response:

A functional approach to this task would be making a variable copy of the original array, iterate each operation making sure each one has two elements (indices) and the first index is less than the second one. Then you can just replace the collection subrange with it reversed subsequence:

func performOperations(arr: [Int], operations: [[Int]]) -> [Int] {
    var arr = arr
    operations.forEach {
        guard $0.count == 2, $0[0] < $0[1] else { return }
        arr.replaceSubrange($0[0]...$0[1], with: arr[$0[0]...$0[1]].reversed())
    }
    return arr
}

let arr = [640, 26, 276, 224, 737, 677, 893, 87, 422, 30]

let operations = [[0, 9], [2, 2], [5, 5], [1, 6], [5, 6], [5, 9], [0, 8], [6, 7], [1, 9], [3, 3]]

performOperations(arr: arr, operations: operations)  // [87, 422, 30, 737, 224, 677, 893, 640, 26, 276]
  • Related