Why is Solution 1 faster than Solution 2?
The input passed to both solutions:
let myArraySortedSquares = Array(stride(from: -100000, through: 100000, by: 1)).shuffled()
Solution 1 with O(nlog(n)) time complexity and O(n) time complexity
Time elapsed: 2.76 s.
// Time: O(nlog(n)) | Space O(n)
func sortedSquaredArray_solution1(_ array: [Int]) -> [Int] {
var sortedSquares = Array(repeating: 0, count: array.count)
for (idx, value) in array.enumerated() {
sortedSquares[idx] = value * value
}
return sortedSquares.sorted()
}
Solution 2 with O(n) time complexity & O(n) time complexity
Time elapsed: 6.67 s.
// Time: O(n) | Space O(n)
func sortedSquaredArray_solution2(_ array: [Int]) -> [Int] {
var sortedSquares = Array(repeating: 0, count: array.count)
var smallerValueIdx : Int = 0
var largerValueIdx : Int = array.count - 1
for idx in stride(from: array.count - 1, through: 0, by: -1) {
if abs(array[smallerValueIdx]) > abs(array[largerValueIdx]) {
sortedSquares[idx] = array[smallerValueIdx] * array[smallerValueIdx]
smallerValueIdx += 1
} else {
sortedSquares[idx] = array[largerValueIdx] * array[largerValueIdx]
largerValueIdx -= 1
}
}
return sortedSquares
}
The problem:
Write a function that takes in a non-empty array of integers that are sorted in ascending order and returns a new array of the same length with the squares of the original integers also sorted in ascending order.
This is solved. the problem I was using has a shuffled array by mistake, not a sorted one...
I also made a blog posting about it: Algorithms & Data structures, Problem #003
sortedSquaredArray_xyd()
to solve? The ones presented are not equivalent for the input described. $\endgroup$O(n) time complexity & O(n) time complexity
looks a copy & paste error,O(nlog(n)) time complexity & O(n) time complexity
inconsistent.) $\endgroup$these are not errors
two statements about time complexity of each procedure where the title mentions space complexity looks erroneous. $\endgroup$a non-empty array of integers that are sorted in ascending order
? $\endgroup$