Sobes.tech
Middle+

// Given two sorted sequences of integers in non-decreasing order. // Return all elements from the first sequence that are not in the second. // 0 <= N <= 10^6 // -10^9 <= a[i] <= 10^9 // [1] // [2, 3, 4, 5, 6] // [1] // [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...] // [1] // [2, 3, 4, 5, 6, 7, 8] func filter(first []int, second []int) []int { res := make([]int, 0, len(first)) i, j := 0, 0 for i < len(first) && j < len(second) { if first[i] < second[j] { result = append(result, first[i]) i++ } else if first[i] > second[j] { j++ } else { i++ j++ } } for i < len(first) { result = append(result, first[i]) i++ } return result }

sobes.tech AI

Answer from AI

The provided Go code has an error: the variable result is not declared, but res is used. You should use the same variable.

Here's the corrected version of the function that returns elements from the first sorted sequence that are not in the second:

func filter(first []int, second []int) []int {
    res := make([]int, 0, len(first))

    i, j := 0, 0

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

    for i < len(first) {
        res = append(res, first[i])
        i++
    }

    return res
}

Algorithm idea:

  • Use two pointers i and j to traverse both sequences.
  • If the element from first is less than the element from second, it means it is not in the second sequence — add it to the result.
  • If the element from first is greater, move pointer j in the second sequence.
  • If they are equal — skip both.
  • After the loop ends, add the remaining elements from first.

The algorithm runs in O(N), which is efficient for large arrays.

// Given two sorted sequences of integers in… - sobes.tech