How to Answer: Create a solution to return a rearranged array.
Advice and answer examples written specifically for a Javascript Beginner Level Arrays job interview.
2. Create a solution to return a rearranged array.
This interview question concentrates on JavaScript functions.
You are given array nums. It contains 2*n elements in form of-
[x1, x2, x3, …, xn, y1, y2, y3, …, yn]
Rearrange the given array to make in form of-
[x1, y1, x2, y2, x3, y3, …, xn, yn]
You have to return the solution in a new array.
/*Example*/
nums = [1,2,3,4,4,3,2,1], n = 4
expected = [1,4,2,3,3,2,4,1]
Solution:
We need to place the first n number to even indices (0-indexed) of the result array, and place next n elements to odd indices. This makes the solution pretty straightforward.
Create a new result array of size 2*n. Copy first n number to even indices, that is 2 * i and other n elements to odd indices, that is 2 * i + 1.
/**
* @param {number[]} nums
* @param {number} n
* @return {number[]}
*/
function rearrageArray(nums, n) {
const result = new Array(2 * n)
for (let i = 0; i < n; i++) {
// first n elements to even indices
result[2 * i] = nums[i]
// other n elements to even indices
result[2 * i + 1] = nums[n + i]
}
return result
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021