703367. Distinct absolute array elements

Easy

Distinct Absolute Array Elements

Summary

Given an array of integers, find and return all distinct absolute elements. The problem is related to arrays and sorting concepts.

Detailed Explanation

In this problem, we are given an array arr containing integer values. We need to find the distinct absolute values from the given array. For example, if the input array is [1, -2, 3, -4], our function should return [1, 2, 3, 4].

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

  1. First, we initialize an empty set distinctAbs to store distinct absolute values.
  2. Then, we iterate over each element in the input array arr.
  3. For each element, we calculate its absolute value using the built-in Math.abs() function in Java and Python, or by directly taking the absolute of the integer value for C++ and JavaScript.
  4. We then add this calculated absolute value to our set distinctAbs. Since sets in most programming languages do not allow duplicate values, this ensures that we only store unique absolute values.
  5. Finally, we convert our set distinctAbs back into a list or array (depending on the language) and return it as the result.

Time complexity for this solution is O(n), where n is the number of elements in the input array. This is because we are iterating over each element once. Space complexity is also O(n) due to the set distinctAbs that stores unique absolute values.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static int[] distinctAbsolute(int[] arr) {
        Set<Integer> distinctAbs = new HashSet<>();
        for (int num : arr) {
            distinctAbs.add(Math.abs(num));
        }
        return distinctAbs.stream().mapToInt(Integer::intValue).toArray();
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.