ismail baig
ismail baig

Reputation: 891

Optimized way to remove duplicate values of a given array

Recently I was asked a very tricky question in an interview.

  1. Given an array like (just for example) enter image description here

  2. Now write an optimized algorithm (without using in build feature except the basic one like for loop etc.) so that the output does not contain duplicate values.

Please Note: Of course we can do it having 2 for loops, but its not optimized. They wanted an optimized solution.

Upvotes: 1

Views: 616

Answers (7)

user2010539
user2010539

Reputation:

`var stringArray = { "0", "1", "5", "65", "r" }; var uniqueStringArray = stringArray.Distinct().ToArray();

Upvotes: 0

Not a bug
Not a bug

Reputation: 4314

In java you can add all elements into Set using Collections#addAll()

Set<T> data = new HashSet<T>();
Collections.addAll(data, yourArray);

PS : Set is a collection that contains no duplicate elements.

Upvotes: 0

Redwan
Redwan

Reputation: 758

You can use modified merge sort. You represent your array as two arrays, and them merge them, but when you find equal values on merge operation you throw out one of them.

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44844

In Java put the Array into Set

see http://docs.oracle.com/javase/7/docs/api/java/util/Set.html

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

For C# you can do:

var result = new HashSet<string>(yourArray);

Upvotes: 0

kbvishnu
kbvishnu

Reputation: 15630

In LinQ its possible

strarray = Your array.
strarray.Distinct().ToArray()

Upvotes: 0

dknaack
dknaack

Reputation: 60506

In c# just use the System.Linq Distinct method.

Sample

var stringArray = { "0", "1", "5", "65", "r" };
var uniqueStringArray = stringArray.Distinct().ToArray();

More Information

Upvotes: 3

Related Questions