1

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.

ismail baig
  • 861
  • 2
  • 11
  • 39

7 Answers7

3

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

Sample

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

More Information

dknaack
  • 60,192
  • 27
  • 155
  • 202
  • 1
    @dknaack: Thanks for the quick answer, actually they have asked to write the algorithm without using inbuilt classes/methods. Or in other words, like implement the DISTINCT() method... :) – ismail baig Jul 09 '14 at 07:18
  • 1
    @ismailbaig I guess he wants the most efficient way to do that. No word about not using inbuilt features. – dknaack Jul 09 '14 at 07:21
  • @dknaack: i have edited the quesiton now as per your comment. – ismail baig Jul 09 '14 at 07:26
1

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.

Redwan
  • 738
  • 9
  • 28
0

In LinQ its possible

strarray = Your array.
strarray.Distinct().ToArray()
kbvishnu
  • 14,760
  • 19
  • 71
  • 101
0

For C# you can do:

var result = new HashSet<string>(yourArray);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

In Java put the Array into Set

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

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

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.

Not a bug
  • 4,286
  • 2
  • 40
  • 80
0

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