Two Pointers Merging sorted arrays

166. Union of Two Sorted Arrays

Medium

You are given two arrays of integers, nums1 and nums2. Each one is sorted in non-decreasing order.

Return every value that appears in at least one of the two arrays, in increasing order. Each value appears in the answer exactly once, even if it repeats inside one array or shows up in both.

Example 1

Input: nums1 = [1, 3, 3, 6, 9] nums2 = [2, 3, 6, 6, 10, 12]

Output: [1,2,3,6,9,10,12]

Explanation: 3 appears three times and 6 appears three times across the two arrays. Each of them appears once in the answer, and the values come out in increasing order.

Example 2

Input: nums1 = [-7, -2, 0, 0], nums2 = [-2, 5]

Output: [-7,-2,0,5]

Explanation: Values can be negative or zero. −2 is in both arrays, and 0 repeats in nums1.

Example 3

Input: nums1 = [4, 4, 4], nums2 = [1, 2]

Output: [1,2,4]

Explanation: The arrays share no value. Every value of nums2 is smaller than every value of nums1, so they come first.

Check your understanding

Work out the answer for this input before you write any code.

nums1 = [2, 2, 5], nums2 = [2, 4, 5, 8]

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • -109 ≤ nums1[i], nums2[i] ≤ 109
  • nums1 and nums2 are each sorted in non-decreasing order.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.