How to find the first repeating element in an array of integers with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Function get_first_repeating_element(ByVal arr As Integer()) As Integer
        Dim x As Integer = -1
        Dim st As HashSet(Of Integer) = New HashSet(Of Integer)()

		For i As Integer = arr.Length - 1 To 0 step -1
            If st.Contains(arr(i)) Then
                x = i
            Else
                st.Add(arr(i))
            End If
        Next

        If x <> -1 Then Return arr(x)
		
        Return -1
    End Function

	Public Shared Sub Main()
        Dim arr As Integer() = New Integer() {1, 2, 4, 5, 6, 5, 4, 3, 7}
        
		Dim n As Integer = get_first_repeating_element(arr)

        If n <> -1 Then
            Console.WriteLine("First repeating element is: " & n)
        Else
            Console.WriteLine("No repeating elements")
        End If
    End Sub
End Class




' run:
'
' First repeating element is: 4
'


 



answered Aug 18, 2022 by avibootz
...