Easy csharp

First duplicate in array #80

Problem

Find first repeated value; print it or -1.

Hints
  • HashSet.Add returns false if exists

Your solution

TestStatusDetails
Ready — edit the code above and click Run or Submit.

Solution

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] a = { 1, 2, 3, 3, 4 };
        var seen = new HashSet<int>();
        foreach (var x in a) {
            if (!seen.Add(x)) { Console.WriteLine(x); return; }
        }
        Console.WriteLine(-1);
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

HashSet detects duplicate on insert.

Discussion

0

Sign in to join the discussion.

No discussions yet — ask the first question!

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details