Blog Overview:

Duplicate elements in an array can lead to data corruption or incorrect outputs in software systems. In this problem, we’ll learn how to detect and remove duplicates efficiently using both Java and Python.

Problem Statement:

Given an array of integers, write a program to remove all duplicate elements while preserving the order of the first occurrence.

Example Input:

Input: [1, 2, 3, 2, 4, 1, 5]  
Output: [1, 2, 3, 4, 5]

Java Solution:

import java.util.*;

public class RemoveDuplicates {
public static List<Integer> removeDuplicates(int[] arr) {
Set<Integer> seen = new LinkedHashSet<>();
for (int num : arr) {
seen.add(num);
}
return new ArrayList<>(seen);
}

public static void main(String[] args) {
int[] input = {1, 2, 3, 2, 4, 1, 5};
List<Integer> result = removeDuplicates(input);
System.out.println("Result: " + result);
}
}

Python Solution:

pythonCopyEditdef remove_duplicates(arr):
seen = set()
output = []
for num in arr:
if num not in seen:
seen.add(num)
output.append(num)
return output

# Test
input_arr = [1, 2, 3, 2, 4, 1, 5]
print("Result:", remove_duplicates(input_arr))

Time Complexity:

Both solutions run in O(n) time using hash sets.

Leave a Reply

Your email address will not be published. Required fields are marked *