878235. Find distinct elements

Easy

Here is a detailed Markdown blog post for the GeeksforGeeks problem "Find distinct elements":

Find Distinct Elements

Summary

The problem is to find all distinct elements from an array. The input array may contain duplicate values, and the output should only include unique values.

Detailed Explanation

To solve this problem, we can use a simple algorithm that involves iterating through the array once. We'll keep track of the elements we've seen so far in a set (in Java or Python) or an unordered_map (in C++). This way, we can quickly check if an element is already present in our result.

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

  1. Initialize an empty set (or unordered_map).
  2. Iterate through the input array.
  3. For each element, check if it's already present in the set (or unordered_map). If not, add it to the set (or unordered_map) and include it in our result.
  4. Return the set (or unordered_map) containing all distinct elements.

Here's a diagram illustrating the algorithm:

  +---------------+
  | Input Array   |
  +---------------+
           |
           v
  +---------------+
  | Initialize Set |
  +---------------+
           |
           v
  +---------------+
  | Iterate through  |
  | array and check  |
  | for duplicates   |
  +---------------+
           |
           v
  +---------------+
  | Add unique       |
  | elements to set  |
  +---------------+
           |
           v
  +---------------+
  | Return distinct|
  | elements        |
  +---------------+

The time complexity of this algorithm is O(n), where n is the length of the input array. This is because we're only iterating through the array once, and each operation (checking for duplicates or adding to the set) takes constant time.

The space complexity is also O(n), as in the worst case, we might need to store all elements in the set (or unordered_map).

Optimized Solutions

Here are some optimized solutions in different languages:

Java

View on GeeksforGeeks
public static int[] findDistinctElements(int[] arr) {
    Set<Integer> distinctElements = new HashSet<>();
    for (int num : arr) {
        if (!distinctElements.contains(num)) {
            distinctElements.add(num);
        }
    }
    return distinctElements.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.