Skip to content

Instantly share code, notes, and snippets.

@SourceCode
Created September 26, 2017 07:32
Show Gist options
  • Select an option

  • Save SourceCode/f04d10f52b938d689a02934120938069 to your computer and use it in GitHub Desktop.

Select an option

Save SourceCode/f04d10f52b938d689a02934120938069 to your computer and use it in GitHub Desktop.
Odd Occurrences in Array - Codibility - C#
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int[] example = { 0, 0, 1, 2, 2, 3, 3, 0, 0, 2, 2, 2, 3, 3, 1, 8 };
var S = new Solution();
Console.WriteLine($"Our Odd Val was {S.solution(example)}");
}
}
class Solution
{
public int solution(int[] A)
{
var dictionary = new Dictionary<int, short>();
int? oddVal = null;
for (var i = 0; i < A.Length; i++)
{
if (dictionary.ContainsKey(A[i]))
{
dictionary[A[i]] = 2;
} else
{
dictionary.Add(A[i], 1);
}
}
foreach (KeyValuePair<int, short> entry in dictionary)
{
if (entry.Value == 1)
{
oddVal = entry.Key;
break;
}
}
return (int)oddVal;
}
}
}
@gaganpa2020
Copy link
Copy Markdown

This code fails some of the performance test and sum up upto 66% correctness only.
image

@vimalsoni265
Copy link
Copy Markdown

This code fails some of the performance test and sum up upto 66% correctness only.
image

Facing the same.

@ajinkyaSurve
Copy link
Copy Markdown

using System;
using System.Linq;

class Solution {
public int solution(int[] A) {
var output = A.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.Where(x=>x.Count % 2 == 1)?.FirstOrDefault()?.Value;

    return output ?? 0;
}

}

@SourceCode
Copy link
Copy Markdown
Author

A lot of this code is from writing (poor) implementations for the first time in C#. By no means should anyone use it for any purpose (it totally sucks).

@chimanwadike
Copy link
Copy Markdown

using System; using System.Linq;

class Solution { public int solution(int[] A) { var output = A.GroupBy(x => x) .Select(g => new {Value = g.Key, Count = g.Count()}) .Where(x=>x.Count % 2 == 1)?.FirstOrDefault()?.Value;

    return output ?? 0;
}

}

This answer is awesome

@PadreSVK
Copy link
Copy Markdown

PadreSVK commented May 15, 2022

This is another simplified solution, that does not handle if there is no "alone" element.

using System;
using System.Linq;

class Solution {
  public int solution(int[] A)
  {
    var result = A.GroupBy(i => i).First(i => i.Count() % 2 == 1).Key;
    return result;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment