0

I was asked in one of the interview that i recently appeared to remove duplicates from unsorted array while still maintaining the order in which they appeared.

For example:

  • Input: int[] nums = [2,1,3,3,2,1,4]
  • Output shud be int[] result = [2,1,3,4]

I tried two options one with Hashset and other with list. But i was still wondering if there is an better optimized solution to this. Appreciate if you can help me out NerdyHB

Here is are solution

public static void main(String[] args) {
    int[] nums = new int[] { 2, 1, 3, 2, 1 };
    List<Integer> result = removeDuplicates(nums);
    System.out.println(result);

    int[] res = removeDuplicatesUsingHashSet(nums);
    System.out.println(Arrays.toString(res));
}

public static List<Integer> removeDuplicates(int[] nums) {
    List<Integer> result = new ArrayList<>();
    for (int n : nums) {
        if (!result.contains(n)) {
            result.add(n);
        }

    }
    return result;
}


public static int[] removeDuplicatesUsingHashSet(int[] nums) {
    HashSet<Integer> hset = new HashSet<>();
    for (int n : nums) {
        hset.add(n);
    }
    int[] result = new int[hset.size()];
    int counter = 0;
    Iterator<Integer> itr = hset.iterator();
    while (itr.hasNext()) {
        result[counter++] = itr.next();
    }

    return result;
}
1
  • 1
    your HashSet solution doesn't preserve order. Commented Aug 31, 2018 at 3:56

2 Answers 2

1

Change the line:

HashSet<Integer> hset = new HashSet<>();

to:

LinkedHashSet<Integer> hset = new LinkedHashSet<>();
Sign up to request clarification or add additional context in comments.

Comments

0
import java.util.Arrays;
public class Main
{
public static void main (String[]args)
{
int[] arr = { 25, 14, 56, 15, 36, 36, 77, 18, 18, 49 };
int size=arr.length;
for(int i=0;i<size;i++)
{
  for(int j=i+1;j<size;j++)
  {
    if(arr[i]==arr[j])
    {
      arr[j]=arr[size-1];
      size--;
    }
 }
  }

 for(int a=0;a<size;a++)
  {
  System.out.print(arr[a]+" ");
  }

 }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.