Quick actions

cmd+k|ctrl+k

Navigation

Languages

Recurring Character in C#

Snippet info

Language

Csharp

Visibility

public

Author

patrykstachowiak

Created

2025-03-07T12:40:57.282278Z

Updated

2025-03-07T12:57:09.201515Z

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

//Google Question
//Given an array = [2,5,1,2,3,5,1,2,4]:
//It should return 2

//Given an array = [2,1,1,2,3,5,1,2,4]:
//It should return 1

//Given an array = [2,3,4,5]:
//It should return undefined

class MainClass {
    static void Main() {
        Console.WriteLine(GetRecurringCharacter(firstArray));
        Console.WriteLine(GetRecurringCharacter(secondArray));
        Console.WriteLine(GetRecurringCharacter(thirdArray));
    }
    
    static int[] firstArray = { 2,5,1,2,3,5,1,2,4 };
    static int[] secondArray = { 2,1,1,2,3,5,1,2,4 };
    static int[] thirdArray = { 2,3,4,5 };
    
    private static int GetRecurringCharacter(int[] array)
    {
        HashSet<int> seenCharacters = new HashSet<int>();
        foreach (var character in array) {
            if (seenCharacters.Contains(character))
            {
                return character;
            } else {
                seenCharacters.Add(character);
            }
        }
        return -1;
    }
}
INFO