Keep last occurrences

Write codeMedium14 min

Your task

Given a list of integers that may contain repeats, produce a new list that keeps only the last occurrence of each distinct value, with the survivors appearing in the same relative order they hold in the original list. For example, [1, 2, 1, 3, 2] keeps the 1 at index 2, the 3 at index 3, and the 2 at index 4, so the answer is [1, 3, 2]. Note this is not the same as keeping first occurrences and cannot be solved by a single forward filter without preparation.

Examples

keep_last_occurrences(nums: list[int]) -> list[int]
Example 1
Inputkeep_last_occurrences([1, 2, 1, 3, 2])
Output[1, 3, 2]