Swap two array without using third array of same size.
Given to array of a and b of the same size. swap arrays without using temp array.
#Implementation:- Time complexity - O(n)
const a = [1, 2, 3, 4 , 5];
const b = [6, 7, 8, 9, 10];
for(let i = 0; i < a.length; i++) {
a[i] = a[i] + b[i]; // a -> 1 + 6 = 7
b[i] = a[i] - b[i]; // b -> 7 - 6 = 1
a[i] = a[i] - b[i]; // a -> 7 - 1 = 6
}
console.log(a, b);
//output - [ 6, 7, 8, 9, 10 ] [ 1, 2, 3, 4, 5 ]
Leave Your Comment