LeetCode 88: Merge Sorted Array Solution
Master LeetCode problem 88 (Merge Sorted Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
88. Merge Sorted Array
Problem Explanation
Explanation
To merge two sorted arrays nums1 and nums2 into nums1 in-place, we can start from the end of both arrays and compare elements. By placing the larger element at the end of nums1, we can ensure that the merged array remains sorted. This approach allows us to merge the two arrays in-place without using any extra space.
- Time complexity: O(m + n) where m is the number of elements in nums1 and n is the number of elements in nums2.
- Space complexity: O(1) as we are merging the arrays in-place.
Solution Code
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}
while (j >= 0) {
nums1[k--] = nums2[j--];
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 88 (Merge Sorted Array)?
This page provides optimized solutions for LeetCode problem 88 (Merge Sorted Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 88 (Merge Sorted Array)?
The time complexity for LeetCode 88 (Merge Sorted Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 88 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 88 in Java, C++, or Python.