Given an integer array nums, return a new array containing only the unique elements from nums, preserving the order of their first occurrence.
An element is considered unique in the output if it appears only once in the result, even if it appeared multiple times in the input. In other words, deduplicate the array while keeping the original ordering of first appearances.
Function Signature
def unique_elements(nums: list[int]) -> list[int]:
Rules
-
Each distinct value of
nums
appears exactly once in the output.
-
Values appear in the order of their first index in
nums
. Do not sort the output.
-
A value that occurs several times in
nums
is still kept, as a single copy. Every distinct value of the input is in the output.
-
An empty
nums
returns an empty list.
Constraints
-
0 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [1,2,2,3,4,4,5]
Output: [1,2,3,4,5]
The second 2 and the second 4 are dropped. Every other entry is the first copy of its value, so the remaining order is unchanged.
Input: nums = [7,7,7,7]
Output: [7]
All four entries are the same value, so only the first copy of 7 remains.
Input: nums = [3,1,3,2,1]
Output: [3,1,2]
The value 3 first appears at index 0, 1 at index 1 and 2 at index 3. The output follows those first positions, which is why it is not in sorted order.