Interleave Two Arrays - Problem
Given two arrays of possibly different lengths, create a new array by interleaving the elements from both arrays.
Start with the first element from the first array, then take the first element from the second array, then the second element from the first array, and so on.
If one array is longer than the other, append the remaining elements from the longer array to the end of the result.
Example: [1,2,3] and [a,b,c,d,e] becomes [1,a,2,b,3,c,d,e]
Input & Output
Example 1 — Basic Interleaving
$
Input:
arr1 = [1,2,3], arr2 = ["a","b","c","d","e"]
›
Output:
[1,"a",2,"b",3,"c","d","e"]
💡 Note:
Start with arr1[0]=1, then arr2[0]="a", then arr1[1]=2, then arr2[1]="b", then arr1[2]=3, then arr2[2]="c". Array 1 is exhausted, so append remaining elements from array 2: "d", "e"
Example 2 — Equal Length Arrays
$
Input:
arr1 = ["x","y"], arr2 = [10,20]
›
Output:
["x",10,"y",20]
💡 Note:
Perfect alternating: "x" from arr1, then 10 from arr2, then "y" from arr1, then 20 from arr2
Example 3 — First Array Longer
$
Input:
arr1 = [1,2,3,4,5], arr2 = ["a"]
›
Output:
[1,"a",2,3,4,5]
💡 Note:
Take 1 from arr1, then "a" from arr2. Array 2 is exhausted, so append remaining elements from arr1: 2,3,4,5
Constraints
- 1 ≤ arr1.length, arr2.length ≤ 1000
- Array elements can be integers or strings
- Total output length = arr1.length + arr2.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code