Loading

LeetCode problem#88

Merge Sorted Array

Solved in 1 languageGo

Solve it on LeetCode(opens in a new tab)

Solution

61 lines
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) []int
  • nums1: The first input array, which contains m sorted elements followed by enough zeros to accommodate the n elements from nums2.
  • m: The number of actual elements in nums1.
  • nums2: The second input array, containing n sorted elements.
  • n: The number of actual elements in nums2.
  • 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}
  1. Variable Initialization:

    • i is initialized to the last index of the actual elements in nums1 (i.e., m-1).
    • j is initialized to the last index of nums2 (i.e., n-1).
    • k is initialized to the last index of the combined array size (m + n - 1).
  2. Main Loop: The loop continues until all elements of nums2 (j >= 0) have been processed.

  3. Comparison and Placement:

    • If nums1[i] is greater than nums2[j], the larger element is placed at position k in nums1.
    • After placing an element, the respective pointer (i or j) is decremented to point to the next element to be considered.
    • The merging is done in reverse order to utilize the empty spaces in nums1 without overwriting any elements that have yet to be processed.

Time and Space Complexity

  • Time Complexity: O(M + N) — The algorithm processes every element of nums1 and nums2 exactly 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 nums1 or nums2 is empty, as well as when both have elements.
  • The assertEqual function 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.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.