714134. Distinct Difference

Medium

Distinct Difference

Summary

The problem "Distinct Difference" involves finding the maximum difference between two distinct elements in a given array. The algorithmic approach requires using a set data structure to keep track of unique elements and their frequencies, allowing for efficient calculation of the maximum difference.

Detailed Explanation

To solve this problem, we will iterate through the array once and store each element along with its frequency in a set. Then, we will find the maximum and minimum values in the set, which represent the two distinct elements. The difference between these two elements is the maximum possible difference.

Here's a step-by-step breakdown of the solution:

  1. Create an empty set to store unique elements.
  2. Iterate through the array, adding each element to the set along with its frequency (set will automatically handle duplicates).
  3. Find the maximum and minimum values in the set.
  4. Calculate the difference between these two values.

The time complexity for this algorithm is O(n), where n is the size of the input array. This is because we only need to iterate through the array once to populate the set. The space complexity is also O(n) as in the worst-case scenario, all elements in the array are unique and hence stored in the set.

          +---------------+
          |  {1, 2, 3, 4}  |
          +---------------+
                  |
                  |  Find max & min
                  v
          +---------------+
          |    Max: 4     |
          |    Min: 1     |
          +---------------+
                  |
                  |  Calculate diff
                  v
          +---------------+
          |   Difference: 3|
          +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static int distinctDifference(int[] arr) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr) {
            set.add(num);
        }
        int max = Collections.max(set);
        int min = Collections.min(set);
        return max - min;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        System.out.println(distinctDifference(arr));
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.