Problem 236798 · medium · Level 02 Linear Data Structures

Remove Duplicates, Keep Last Seen

arrays · sets · ordering

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.
  • 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
Starting Python…