#2670

Find the Distinct Difference Array

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses two passes through the array to maintain counts of distinct elements in a single pass for both prefix and suffix, leveraging a HashMap for efficiency.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a frequency map to count occurrences of each element in the array.
  2. 2Step 2: Initialize two variables: 'prefixCount' for distinct elements in the prefix and 'suffixCount' for distinct elements in the suffix.
  3. 3Step 3: Calculate the initial suffixCount based on the frequency map.
  4. 4Step 4: Iterate through the array, updating prefixCount and suffixCount as you go, and calculate diff[i] as prefixCount - suffixCount.
  5. 5Step 5: Update the frequency map as you include elements in the prefix.
  6. 6Step 6: Return the 'diff' list.
solution.py22 lines
1# Full working Python code
2
3def distinctDifferenceArray(nums):
4    from collections import Counter
5    n = len(nums)
6    diff = []
7    freq = Counter(nums)
8    suffixCount = len(freq)
9    prefixCount = 0
10
11    for i in range(n):
12        if freq[nums[i]] == 1:
13            suffixCount -= 1
14        freq[nums[i]] -= 1
15        if freq[nums[i]] == 0:
16            del freq[nums[i]]
17        prefixCount += 1
18        diff.append(prefixCount - suffixCount)
19    return diff
20
21# Example usage
22print(distinctDifferenceArray([1,2,3,4,5]))

Complexity note: The time complexity is O(n) because we make a single pass through the array to build the frequency map and another pass to compute the distinct counts. The space complexity is O(n) due to the storage of the frequency map.

  • 1Using a frequency map helps efficiently track distinct elements.
  • 2Two passes through the array can optimize the counting process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.