Tutorialspoint
Problem
Solution
Submissions

Merge Two Sorted Arrays

Certification: Basic Level Accuracy: 40% Submissions: 5 Points: 5

Write a C# program to merge two sorted arrays into a single sorted array. Given two arrays, nums1 and nums2, which are sorted in ascending order, and two integers m and n representing the number of elements in nums1 and nums2, respectively, merge nums2 into nums1 as one sorted array.

Example 1
  • Input: nums1 = [1,3,5,0,0,0], m = 3, nums2 = [2,4,6], n = 3
  • Output: [1,2,3,4,5,6]
  • Explanation: The arrays [1,3,5] and [2,4,6] are merged into [1,2,3,4,5,6].
Example 2
  • Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
  • Output: [1,2,2,3,5,6]
  • Explanation: The arrays [1,2,3] and [2,5,6] are merged into [1,2,2,3,5,6].
Constraints
  • nums1.length == m + n
  • nums2.length == n
  • 0 ≤ m, n ≤ 200
  • 1 ≤ m + n ≤ 200
  • -10^9 ≤ nums1[i], nums2[j] ≤ 10^9
  • Time Complexity: O(m+n)
  • Space Complexity: O(1)
ArraysControl StructuresDeloitteSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Start from the end of both arrays and work backwards.
  • Compare elements and place the larger one at the end of nums1.
  • Continue until all elements from nums2 are placed in the correct position.
  • If there are remaining elements in nums2, copy them to nums1.


Submitted Code :