Sobes.tech
Middle+

// Given sorted slices A and B. Slices keep unique values. Produce a union of them into sorted slice RES without duplicates. // A = [1, 3, 5, 7] // B = [1, 2, 3, 7, 9] // RES = [1, 2, 3, 5, 7, 9]

sobes.tech AI

Answer from AI

To merge two sorted slices with unique values into one sorted slice without duplicates, you can use a merging algorithm similar to the merge step in merge sort.

Idea:

  • Traverse both slices simultaneously with two indices.
  • Compare the current elements, add the smaller one to the result, and move the corresponding index.
  • If the elements are equal, add one of them and advance both indices.

Example in Go:

func unionSortedSlices(A, B []int) []int {
    i, j := 0, 0
    res := make([]int, 0, len(A)+len(B))

    for i < len(A) && j < len(B) {
        if A[i] < B[j] {
            res = append(res, A[i])
            i++
        } else if A[i] > B[j] {
            res = append(res, B[j])
            j++
        } else { // A[i] == B[j]
            res = append(res, A[i])
            i++
            j++
        }
    }

    // Add remaining elements
    for i < len(A) {
        res = append(res, A[i])
        i++
    }
    for j < len(B) {
        res = append(res, B[j])
        j++
    }

    return res
}

This code guarantees that the resulting slice will contain all unique elements from A and B, sorted in ascending order.

// Given sorted slices A and B. Slices keep unique… - sobes.tech