Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time/space complexity of ES6 array swap?

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?

like image 407
Kevin Arthur Avatar asked Oct 17 '22 05:10

Kevin Arthur


1 Answers

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.

like image 179
Barmar Avatar answered Oct 20 '22 04:10

Barmar