Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Merge Sorted Arrays

Easy Acceptance 32.01% Points 20

You are given two sorted arrays, a[] and b[], both arranged in non-decreasing order. The task is to merge these arrays into a single sorted array without using extra space. Modify a so that it contains the first n elements and modify b so that it contains the last m elements.

Examples
Example 1

Example 1

Input: a[] = [2, 4, 7, 10], b[] = [2, 3]

Output: 2 2 3 4 7 10

Explanation: After merging the two non-decreasing arrays, we get, 2 2 3 4 7 10

Example 2

Example 2

Input: a[] = [1, 5, 9, 10, 15, 20], b[] = [2, 3, 8, 13]

Output: 1 2 3 5 8 9 10 13 15 20

Explanation: After merging two sorted arrays we get 5 10 12 18 20.

Constraints
  • 1 <= a.size(), b.size() <= 10^5
  • 0 <= a[i], b[i] <= 10^7
Hints
  • Expected Time Complexity O(n log m)
  • Expected Space Complexity O(1)
Topics
Array Sorting Algorithms
Companies
Microsoft Adobe Linkedin Goldman Sachs Zoho
Added 30 Nov 2024 32.01% acceptance
Ln 1, Col 1Sign in to save your code
2 4 7 10
2 3
2 2 3 4 7 10