LeetCode problem#88
Merge Sorted Array
Solved in 1 languageGo
Solution
1package main
2
3import (
4 "fmt"
5 "os"
6)
7
8// time O(M + N)
9// space O(1)
10func merge(nums1 []int, m int, nums2 []int, n int) []int {
11 for i, j, k := m-1, n-1, m+n-1; j >= 0; k -= 1 {
12 if i >= 0 && nums1[i] > nums2[j] {
13 nums1[k] = nums1[i]
14 i--
15 } else {
16 nums1[k] = nums2[j]
17 j--
18 }
19 }
20
21 return nums1
22}
23
24func assertEqual(a int, b int) {
25 if a != b {
26 fmt.Printf("Expected %d, but got %d\n", a, b)
27 os.Exit(1)
28 }
29}
30
31func test() {
32 testcase1 := merge([]int{1, 2, 3, 0, 0, 0}, 3, []int{2, 5, 6}, 3)
33 assertEqual(testcase1[0], 1)
34 assertEqual(testcase1[1], 2)
35 assertEqual(testcase1[2], 2)
36 assertEqual(testcase1[3], 3)
37 assertEqual(testcase1[4], 5)
38 assertEqual(testcase1[5], 6)
39 assertEqual(len(testcase1), 6)
40
41 testcase2 := merge([]int{1}, 1, []int{}, 0)
42 assertEqual(testcase2[0], 1)
43 assertEqual(len(testcase2), 1)
44
45 testcase3 := merge([]int{0}, 0, []int{1}, 1)
46 assertEqual(testcase3[0], 1)
47 assertEqual(len(testcase3), 1)
48
49 testcase4 := merge([]int{4, 5, 6, 0, 0, 0}, 3, []int{1, 2, 3}, 3)
50 assertEqual(testcase4[0], 1)
51 assertEqual(testcase4[1], 2)
52 assertEqual(testcase4[2], 3)
53 assertEqual(testcase4[3], 4)
54 assertEqual(testcase4[4], 5)
55 assertEqual(testcase4[5], 6)
56 assertEqual(len(testcase4), 6)
57}
58
59func main() {
60 test()
61}How it works
The provided code is a solution to the problem of merging two sorted arrays in Go, often found on platforms like LeetCode. This problem typically requires merging two arrays (nums1 and nums2) into a single sorted array. The nums1 array has sufficient space (placeholder zeros) to accommodate the elements from nums2.
Here's a breakdown of the solution, including the main parts of the code:
Function Signature
func merge(nums1 []int, m int, nums2 []int, n int) []intnums1: The first input array, which containsmsorted elements followed by enough zeros to accommodate thenelements fromnums2.m: The number of actual elements innums1.nums2: The second input array, containingnsorted elements.n: The number of actual elements innums2.- The function returns the merged array.
Merge Logic
1for i, j, k := m-1, n-1, m+n-1; j >= 0; k -= 1 {
2 if i >= 0 && nums1[i] > nums2[j] {
3 nums1[k] = nums1[i]
4 i--
5 } else {
6 nums1[k] = nums2[j]
7 j--
8 }
9}-
Variable Initialization:
iis initialized to the last index of the actual elements innums1(i.e.,m-1).jis initialized to the last index ofnums2(i.e.,n-1).kis initialized to the last index of the combined array size (m + n - 1).
-
Main Loop: The loop continues until all elements of
nums2(j>= 0) have been processed. -
Comparison and Placement:
- If
nums1[i]is greater thannums2[j], the larger element is placed at positionkinnums1. - After placing an element, the respective pointer (
iorj) is decremented to point to the next element to be considered. - The merging is done in reverse order to utilize the empty spaces in
nums1without overwriting any elements that have yet to be processed.
- If
Time and Space Complexity
- Time Complexity: O(M + N) — The algorithm processes every element of
nums1andnums2exactly once. - Space Complexity: O(1) — The merge is done in place, meaning no additional space is required beyond a few variables.
Test Function
The test() function runs several test cases to verify that the merge function works correctly:
- Test cases check various scenarios, including when either
nums1ornums2is empty, as well as when both have elements. - The
assertEqualfunction checks if the expected output matches the actual output and prints an error message if they do not.
Main Function
Finally, the main function simply calls the test() function to execute the test scenarios.
Summary
This implementation efficiently merges two sorted arrays using a reverse traversal approach, operates in O(M + N) time while being in-place, thus requiring minimal additional memory. The accompanying tests ensure the correctness of the implementation across different scenarios.
Written by AI from the code above, so double-check anything important.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.