Find the Distinct Difference Array — LeetCode 2670 Python Solution
- Problem
- #2670
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed array nums of length n. The distinct difference array of nums is an array diff of length n such that diff[i] is equal to the number of distinct elements in the suffix nums[i + 1, ..., n - 1] subtracted from the number of distinct elements in the prefix nums[0, ..., i].
Example
- Input
- nums = [1,2,3,4,5]
- Output
- [-3,-1,1,3,5]
- Explanation
- For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3.
Python solution
class Solution:
def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
n = len(nums)
suf = [0] * (n + 1)
s = set()
for i in range(n - 1, -1, -1):
s.add(nums[i])
suf[i] = len(s)
s.clear()
ans = [0] * n
for i, x in enumerate(nums):
s.add(x)
ans[i] = len(s) - suf[i + 1]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2670. Find the Distinct Difference Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2670. Find the Distinct Difference Array?
- LeetCode 2670. Find the Distinct Difference Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2670. Find the Distinct Difference Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2670. Find the Distinct Difference Array?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2670. Find the Distinct Difference Array cover?
- LeetCode 2670. Find the Distinct Difference Array is tagged Array and Hash Table on LeetCode.