Merge Sorted Array Leetcode Solution
Merge Sorted Array Leetcode Problem :
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Merge Sorted Array Leetcode Solution :
Constraints :
- nums1.length == m + n
- nums2.length == n
- 0 <= m, n <= 200
- 1 <= m + n <= 200
- -10^9 <= nums1[i], nums2[j] <= 10^9
Example 1:
- Input: nums1 = [1], m = 1, nums2 = [], n = 0
- Output: [1]
Example 2:
- Input: nums1 = [0], m = 0, nums2 = [1], n = 1
- Output: [1]
Intuition :
We are given two sorted arrays nums1 and nums2 of sizes m and n, respectively. We need to merge these two arrays into a single sorted array, and the result should be stored inside nums1. Since nums1 is of size m+n, we can use this extra space to store the merged array. We can iterate through the arrays from the end and place the larger element in the end of nums1.
Approach :
- Traverse through nums2 and append its elements to the end of nums1 starting from index m.
- Sort the entire nums1 array using sort() function.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class Solution { public: void merge(vector< int>& nums1, int m, vector< int>& nums2, int n) { for (int j = 0, i = m; j< n; j++){ nums1[i] = nums2[j]; i++; } sort(nums1.begin(),nums1.end()); } };
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { for (int j = 0, i = m; j < n; j++) { nums1[i] = nums2[j]; i++; } Arrays.sort(nums1); } }
class Solution(object): def merge(self, nums1, m, nums2, n): for j in range(n): nums1[m+j] = nums2[j] nums1.sort()
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment