Given a list nums, return a new list containing each distinct value once, keeping only the last occurrence of each value. The kept elements must appear in the same order as those last occurrences appear in nums.
Examples
Input: nums = [3, 1, 3, 2, 1]
Output: [3, 2, 1]
Explanation: the last 3 is at index 2, the last 2 at index 3, the last 1 at index 4.
Input: nums = [1, 2, 1, 2, 1, 2]
Output: [1, 2]
Constraints
0 <= len(nums) <= 10**5- Elements are hashable (ints or strings).
- Return a new list; do not modify
nums. One test callsnums_after(nums), which runs yourunique_keep_last, appends an item to the list you returned and then returnsnumsitself, so it must come back unchanged. - Target: O(n) time.
Goals
- Keep the last occurrence of each value rather than the first
- Use a reverse scan to turn 'last' into 'first'
- Restore the original orientation of the result