This week’s question:
Given a list, swap every two adjacent nodes. Something to think about: How would your code change if this were a linked list, versus an array?
Example:
swapPairs([1,2,3,4])
[2,1,4,3]
swapPairs([])
[]
My thought process
When I looked at this, it seemed pretty straight-forward. Immediately there were a few things I could gather from the examples and one thing I wasn't sure about.
Things we know
- The
swapPairs
function should always return an array - Grab every other index, push it to a new array, then push the previous index's contents
Things we don't know
- What happens when there's an odd number of items in the array? ex:
[1,2,3,4,5]
I ended up trying to grab each second pair's index (ex: 1, 3, 5, etc) which are all the odd indexes. I then push that into a new array, then push the previous index's contents into the new array. This only happens if there's an even number of items in the array total.
This way, if there's an odd number of items in the array, when we check to see if the index is odd, it'll return false and items won't be pushed to the new array.
My solution
function swapPairs(array) {
let newArray = [];
array.forEach((el, index) => {
if (index % 2 == 1) {
newArray.push(el);
newArray.push(array[index-1]);
}
});
return newArray;
}
swapPairs([1,2,3,4]);
[2, 1, 4, 3]
swapPairs([1,2,3,4,7,9,9,9,11,12,14,51]);
[2, 1, 4, 3, 9, 7, 9, 9, 12, 11, 51, 14]