So you can swap array elements using ES6 with the following notation:
let a = [1, 2, 3, 4];
[a[0], a[1]] = [a[1], a[0]];
console.log(a); // [2, 1, 3, 4];
But I'm curious to know the time/space complexity of this.
If it's just syntactic sugar for:
var temp = a[0];
a[0] = a[1];
a[1] = temp;
Then I'd imagine it's O(1) for both time and space.
I suppose even if we are creating a whole new array to make the destructuring and then assignment, would still all be constant since we're only ever swapping a couple of elements. Does this sound right?
It's probably more like:
var temp1 = a[1];
var temp2 = a[0];
a[0] = temp1;
a[1] = temp2;
Although temp1
isn't really needed when just swapping two values, I wouldn't expect the compiler to be able to figure out which temporaries are needed and which aren't in more general cases.
But either way, it's O(n)
, where n
is the number of elements you're swapping. Any intermediate temporaries are just a constant factor, they don't affect the time complexity.
I suppose it does affect space complexity -- if the compiler could detect that only one temporary is needed, it would be O(1)
space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With