Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Merge Sorted Arrays

Easy Acceptance 32.01% Points 20.00

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.

Hints
Hint 1
Expected Time Complexity O(n log m)
Hint 2
Expected Space Complexity O(1)
Constraints
  • 1 <= a.size(), b.size() <= 10^5
  • 0 <= a[i], b[i] <= 10^7
Companies
Microsoft Adobe Linkedin Goldman Sachs Zoho
Topics
Array Sorting Algorithms
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions