Skip to content

Instantly share code, notes, and snippets.

@thieunguyencrystal
Last active March 19, 2019 07:48
Show Gist options
  • Save thieunguyencrystal/9979246487585bd2c1ae4eb537c0edfe to your computer and use it in GitHub Desktop.
Save thieunguyencrystal/9979246487585bd2c1ae4eb537c0edfe to your computer and use it in GitHub Desktop.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
/*
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
*/
import UIKit
// 01 a1 a2 a3
// a0 01 a2 a3
// a0 a1 01 a3
// a0 a1 a2 01
var array = [1, 2, 3]
let count = array.count
// Solution 1:
var left: [Int] = Array(repeating: 1, count: count)
var right: [Int] = Array(repeating: 1, count: count)
var result: [Int] = Array(repeating: 1, count: count)
for i in (1..<count) {
left[i] = left[i-1] * array[i-1]
}
left
for i in (0..<count-1).reversed() {
right[i] = right[i+1] * array[i+1]
}
right
for i in (0..<count) {
result[i] = left[i] * right[i]
}
result
// Solution 2:
var output: [Int] = Array(repeating: 1, count: count)
var temp = 1
for i in (1..<count) {
output[i] = temp * array[i-1]
temp = output[i]
}
temp = 1
for i in (0..<count-1).reversed() {
output[i] = temp * array[i+1]
temp = output[i]
}
output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment