HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Count duplicates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
countduplicatesstackoverflow

Problem

Problem statement:


Given an array of unknown size and containing only integers between 0 to 30 (inclusive), write an algorithm to find which numbers are duplicated, if any

My solution in C#:

public IEnumerable Duplicates(int[] sequence)
{
    var targets = new Dictionary();
    foreach (var n in sequence)
        if (targets.ContainsKey(n))
            targets[n]++;
        else
            targets.Add(n, 1);
    return targets.Where(kv => kv.Value > 1).Select(kv => kv.Key);   
}


I would welcome any potential flaws or improvements.

Solution

I would do something along these lines.
I'm not that sharp on C# but anyway...

The main idea here is to use an int array instead of a Dictionary. This uses the fact that all values are between 0 and 30 (inclusive)

public List Duplicates(int[] sequence)
{
    int[] countArr = new int[31];
    for (int i in sequence)
    {
        countArr[i]++;
    }

    List resultList = new List();

    for (int i in countArr)
    {
        if (countArr[i] > 1)
        {
            resultList.Add(i);
        }
    }

    return resultList;
}


It's dangerously close to what you did, except i'm not using a dictionary or any other fancy C# features. ;)

Code Snippets

public List<int> Duplicates(int[] sequence)
{
    int[] countArr = new int[31];
    for (int i in sequence)
    {
        countArr[i]++;
    }

    List<int> resultList = new List<int>();

    for (int i in countArr)
    {
        if (countArr[i] > 1)
        {
            resultList.Add(i);
        }
    }

    return resultList;
}

Context

StackExchange Code Review Q#84145, answer score: 12

Revisions (0)

No revisions yet.