Merge two arrays alternately

Merge two arrays alternately

Medium Java Java Arrays 18 views
Explanation Complexity

Problem Statement

Task: merge a and b alternately into a new array. Extra tail should be appended at end.

Input Format

An integer n (size of array a)
Then n integers
An integer m (size of array b)
Then m integers

Output Format

A new array formed by merging a and b alternately.
If one array finishes early, append remaining elements of the other.

Example

3
1 2 3
5
10 20 30 40 50
[1, 10, 2, 20, 3, 30, 40, 50]

Constraints

• n ≥ 0, m ≥ 0

• Must create a new array

Concept Explanation

We take one element from a, then one from b,
continue alternately.
If one array ends, add remaining elements of the other.

Step-by-Step Explanation

1.Read arrays a and b.

2.Create new array of size n + m.

3.Initialize indices: i = 0, j = 0, k = 0.

4.While both arrays have elements:

• Add a[i] to result, increment i, k.

• Add b[j] to result, increment j, k.

5.While i < n:

• Add remaining elements of a.

6.While j < m:

• Add remaining elements of b.

7.Return the new array.

Concept Explanation

We take one element from a, then one from b,
continue alternately.
If one array ends, add remaining elements of the other.

Step-by-Step Explanation

1.Read arrays a and b.

2.Create new array of size n + m.

3.Initialize indices: i = 0, j = 0, k = 0.

4.While both arrays have elements:

• Add a[i] to result, increment i, k.

• Add b[j] to result, increment j, k.

5.While i < n:

• Add remaining elements of a.

6.While j < m:

• Add remaining elements of b.

7.Return the new array.

Input / Output Format

Input Format
An integer n (size of array a)
Then n integers
An integer m (size of array b)
Then m integers
Output Format
A new array formed by merging a and b alternately.
If one array finishes early, append remaining elements of the other.
Constraints
• n ≥ 0, m ≥ 0

• Must create a new array

Examples

Input:
3 1 2 3 5 10 20 30 40 50
Output:
[1, 10, 2, 20, 3, 30, 40, 50]

Example Solution (Public)

Java
static int[] mergeAlternate(int[] a,int[] b){int[] r=new int[a.length+b.length];int i=0,j=0,k=0;while(i<a.length||j<b.length){if(i<a.length) r[k++]=a[i++];if(j<b.length) r[k++]=b[j++];}return r;}

Official Solution Code

static int[] mergeAlternate(int[] a,int[] b){int[] r=new int[a.length+b.length];int i=0,j=0,k=0;while(i<a.length||j<b.length){if(i<a.length) r[k++]=a[i++];if(j<b.length) r[k++]=b[j++];}return r;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.