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
Interleave Two ArraysINPUTArray 1:123Array 2:abcdeDifferent lengths:arr1.length = 3arr2.length = 5ALGORITHM STEPS1Initialize two pointers2Alternate: arr1 → arr2 → arr13Handle different lengths4Append remaining elementsSequence:1 → a → 2 → b → 3 → cThen append: d, eFINAL RESULTInterleaved Array:1a2b3cdeLength: 8 elements(3 + 5 = 8)Key Insight:Two pointers with alternating flag elegantly handles different array lengths without complex indexingTutorialsPoint - Interleave Two Arrays | Two Pointers Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~12 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen