Sample Problem: Print distinct elements in Java

 Problem: You have a list of numbers that may have some repeated numbers in it. You need to find and print all the unique numbers in the list, which means that you only want to print each number once.

Example:

Input: [4, 8, 5, 8, 7, 5] Output: [4, 8, 5, 7]

Input: [10, 8, 4, 10, 10, 4] Output: [10, 8, 4]

Explanation: In both examples, some numbers are repeated, and we remove the duplicates to only keep the unique numbers.

Approach:

To solve this problem, we can use a HashSet. A HashSet is a data structure that only stores unique elements. We can iterate over the list of numbers and add each number to the HashSet. If the number is already in the HashSet, we skip it. At the end, the HashSet will only contain the unique numbers, and we can print them out.

Implementation:

Here is a code example in Java:

import java.util.*;

public class PrintUniqueNumbers {

java
static void printDistinctNumbers(int arr[]) { HashSet<Integer> set = new HashSet<Integer>(); for(int i=0; i<arr.length; i++) { if(!set.contains(arr[i])) { System.out.print(arr[i] + " "); set.add(arr[i]); } } } public static void main(String[] args) { int arr[] = {10, 8, 4, 10, 10, 4}; printDistinctNumbers(arr); }

}

Output: 10 8 4

Time Complexity: The time taken for inserting elements in the HashSet is O(N), and accessing an individual element from the HashSet is O(1). In the worst case, it can take O(N) time for traversing the HashSet if all the elements in the array are unique.

Previous Post Next Post