[
array
hash table
]
BinarySearch 0396 Remove Last Duplicate Entries
Problem statement
https://binarysearch.com/problems/Remove-Last-Duplicate-Entries/
Solution
For each element keep places where we have it. Also keep boolean array of taken, which have 1
in the beginning. Then iterate through values and if we have more than one, update last element of taken
.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def solve(self, nums):
n = len(nums)
d = defaultdict(list)
taken = [1] * n
for i, x in enumerate(nums):
d[x] += [i]
for val in d:
if len(d[val]) > 1:
taken[d[val][-1]] = 0
return [nums[i] for i in range(n) if taken[i]]