What is the micro-optimal and most elegant way to return List <string> elements that occurs only once in another List <string>

That was the interview question I had today:

"Given a list of strings, return a list of only unique strings

I'm curious what answer would be certified by Skeet.

My own answer was

public static List<string> sans_repeats ( List<string> input ) 
{
    Dictoinary<string,int> counter = new Dictionary<string,int>();
    List<string> output = new List<string>();
    foreach ( string S in input ) 
    {
       if ( counter.HasKey(S) ) counter[S] = 1;
       else ++count[S];
    }     
    foreach ( KeyValuePair<string,int> entry in counter ) 
       if ( entry.Value == 1 ) output.Add(entry.Key);
    return output;
}

and the interview said

"Well, this is one way to do this ..."

in a voice that seemed condescending, as if I were doing something wrong.

  • Is there anything logically wrong with this?
  • Is there a way to achieve a more efficient solution for working with memory and processing?
  • Is it possible that the interviewer is looking for a LINQ-esque solution? Why didn’t I like him?
  • Is there any way to make this more compact?
+4
5

, LINQ:

var src = new List<string>() { "dog", "cat", "elephant", "dog", "dog" } ;
src.GroupBy(x => x).Where(y => y.Count() == 1).ToList();

+6

:

List<string> distinctList = input.Distinct();

https://msdn.microsoft.com/library/bb920306(v=vs.90).aspx

, , :

List<string> output = new List<string>();
foreach (string S in input) 
{
    if (output.Contains(S)) continue;       
    output.Add(S);
}

Edit

, , :

Dictionary<string, int> stringCount = new Dictionary<string, int>();
foreach (string S in input) 
{
    if (stringCount.ContainsKey(S))
    {
        stringCount[S]++;
    }
    else
    {
        stringCount.Add(S, 1);
    }       
}

var output = stringCount.Where(x => x.Value == 1).ToList();
+3

, , .

  • LINQ, LINQ. ( )

  • , C . , , . output . , . , counter , int[], .

  • . , :

    (1) , , , ?

    (2) ? , byte[] int[].

+2

Linq - , , Dictionary, HashSet.

var strings = new[] { "a", "a", "b", "c" };
var hash = new HashSet<string>(strings);
hash.Dump(); // a, b, c
0

, , HashSet.Add true, . .

var uniqueSet = new HashSet<string>();
var duplicateSet = new HashSet<string>(input.Where(item => !uniqueSet.Add(item)));
var output = input.Where(item => !duplicateSet.Contains(item)).ToList();
0

Source: https://habr.com/ru/post/1618233/


All Articles