Find the Distinct Difference Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
        cnt = [0] * 51
        dist = 0
        res = []
        for n in nums:
            res.append((res[-1] if res else 0) + (1 if cnt[n] == 0 else 0))
            cnt[n] += 1
        for i in range(len(nums) - 1, 0, -1):
            dist += 1 if cnt[nums[i]] > 0 else 0
            cnt[nums[i]] = 0
            res[i - 1] -= dist
        return res

Here’s a brief explanation of the code:

  • cnt is an array that keeps track of the count of each element in nums.
  • dist keeps track of the number of distinct elements in the suffix.
  • The first loop computes the cumulative count of distinct elements from the beginning of the array and stores it in res.
  • The second loop modifies the result by considering the distinct elements in the suffix.
  • The exchange part of the original code is implemented using separate statements in Python.