DEV Community

Cover image for C# LeetCode 136: Single Number - (Easy)
Grant Riordan
Grant Riordan

Posted on

C# LeetCode 136: Single Number - (Easy)

Problem

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Approach & Initial Thinking

Seems pretty simple, we need to count each number in the array and then return the one with the least count.

My first go-to is again LINQ - you can learn more about LINQ in my FreeCodeCamp tutorial here

We can use a combination of the GroupBy and OrderBy() Count() to count all the individual numbers and order them by count.

All we have to do then is return the First() (lowest scoring) key (key is what we've grouped by).

Code

public int SingleNumber(int[] nums)
{
    return nums
        .GroupBy(x => x)
        .OrderBy(g => g.Count())
        .First()
        .Key;
}
Enter fullscreen mode Exit fullscreen mode

Drop me a follow on twitter/x to hear about more articles in this series and other tech / developer tips.

Top comments (0)