Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2670. Find the Distinct Difference Array

ArrayHash Table

Explanation

To solve this problem, we need to iterate through the array from left to right and calculate the distinct difference for each index. For each index i, we count the number of distinct elements in the prefix nums[0, ..., i] and the number of distinct elements in the suffix nums[i + 1, ..., n - 1]. Then, we subtract the count of distinct elements in the suffix from the count of distinct elements in the prefix to get the distinct difference for that index.

We can use a set data structure to keep track of distinct elements in the prefix and suffix as we iterate through the array. By adding elements to the set as we move forward in the array and removing elements as we move backward, we can efficiently calculate the distinct elements in the prefix and suffix.

Time complexity: O(n) where n is the length of the input array nums. Space complexity: O(n) for the sets used to store distinct elements in the prefix and suffix.

import java.util.*;

class Solution {
    public int[] distinctDifferenceArray(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        
        for (int i = 0; i < n; i++) {
            Set<Integer> prefixSet = new HashSet<>();
            Set<Integer> suffixSet = new HashSet<>();
            int prefixCount = 0, suffixCount = 0;
            
            for (int j = 0; j < i; j++) {
                if (!prefixSet.contains(nums[j])) {
                    prefixSet.add(nums[j]);
                    prefixCount++;
                }
            }
            
            for (int j = i + 1; j < n; j++) {
                if (!suffixSet.contains(nums[j])) {
                    suffixSet.add(nums[j]);
                    suffixCount++;
                }
            }
            
            result[i] = prefixCount - suffixCount;
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.