Concatenate Two Arrays

Problem

Given two arrays sorted in ascending order, write a program that merges the two arrays in ascending order and prints them.

input

  • The first line gives the size N (1<=N<=100) of the first array.
  • The second line gives the N array elements in ascending order.
  • The third line gives the size M (1<=M<=100) of the second array.
  • The fourth line gives the M array elements in ascending order.
  • Each list element does not exceed the size of an int variable.
3
1 3 5
5
2 3 6 7 9

output

Outputs an array sorted in ascending order.

1 2 3 3 5 6 7 9

Solution

O(nlogn) : using dot spread & sort()

function solution(arr1, arr2) {
	return [...arr1, ...arr2].sort((a, b) => a - b);
}

O(n+m) : Two Pointers Algorithm

function solution(arr1, arr2) {
	let answer = [];
	let n = arr1.length,
		m = arr2.length,
		p1 = (p2 = 0);

	while (p1 < n && p2 < m) {
		// answer.push(arr1[p1++]) means push arr1[p1] first, then increase p1
		// e.g) arr.push(3++) is arr.push(3) then it is gonna be 4
		if (arr1[p1] <= arr2[p2]) answer.push(arr1[p1++]);
		else answer.push(arr2[p2++]);
	}

	while (p1 < n) answer.push(arr1[p1++]);
	while (p2 < m) answer.push(arr2[p2++]);

	return answer;
}