127. Combine Integer Arrays / Lists

Asked in

Combine Integer Arrays / Lists
Combine two integer lists into one without repeating elements.

You are given two integer lists nums1 and nums2. Both lists may contain duplicate values.

Return a new list that contains each distinct integer exactly once, while preserving the order of first appearance across the two input lists.

If a value has already been added to the result, it must not be added again.

You must solve this problem without using any set or map like HashSet or HashMap.

Method Signature

List<Integer> combineArrays(List<Integer> nums1, List<Integer> nums2)

  • Return a List<Integer> containing all distinct integers from nums1 and nums2, in the order they are first seen.
  • Keep only the first occurrence of each value.
  • Duplicates across the two lists must also be ignored after the first occurrence.

Constraints

  • 0 ≤ nums1.size(), nums2.size() ≤ 10^4
  • -10^9 ≤ nums1[i], nums2[i] ≤ 10^9
  • Both input lists may contain duplicate values.

Examples

Example 1

Input:
combineArrays(nums1 = [1, 2, 3, 4, 5, 1, 2], nums2 = [5, 6, 7, 8])

Output:
[1, 2, 3, 4, 5, 6, 7, 8]

Explanation:
Values 1, 2, 3, 4, 5 are added from nums1 in order. The second 1 and second 2 are ignored. In nums2, 5 is already present, so it is ignored. Then 6, 7, 8 are added.

Example 2

Input:
combineArrays(nums1 = [4, 4, 4], nums2 = [4, 4])

Output:
[4]

Explanation:
Only the first occurrence of 4 is kept.

Example 3

Input:
combineArrays(nums1 = [], nums2 = [2, 1, 2, 3, 1])

Output:
[2, 1, 3]

Explanation:
Since nums1 is empty, the result is built only from nums2. Each value is included only the first time it appears.

Example 4

Input:
combineArrays(nums1 = [9, 8, 7], nums2 = [7, 8, 9, 10])

Output:
[9, 8, 7, 10]

Explanation:
The values 9, 8, 7 are taken from nums1. In nums2, 7, 8, 9 are skipped because they already exist in the result. Then 10 is added.




Please use Laptop/Desktop or any other large screen to add/edit code.