Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to find the length of the longest consecutive sequence of an unsorted array of integers in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class LongestConsecutiveSequence
    Public Shared Function LongestConsecutive(ByVal nums As Integer()) As Integer
        Dim numSet As HashSet(Of Integer) = New HashSet(Of Integer)(nums)
        Dim longestStreak As Integer = 0

        For Each num As Integer In numSet

            If Not numSet.Contains(num - 1) Then
                Dim currentNum As Integer = num
                Dim currentStreak As Integer = 1

                While numSet.Contains(currentNum + 1)
                    currentNum += 1
                    currentStreak += 1
                End While

                longestStreak = Math.Max(longestStreak, currentStreak)
            End If
        Next

        Return longestStreak
    End Function

    Public Shared Sub Main()
        Dim nums As Integer() = {680, 4, 590, 3, 2, 1}
	
        Dim result As Integer = LongestConsecutive(nums)
        Console.WriteLine("Length of the longest consecutive sequence: " & result)
    End Sub
End Class




' run:
'
' Length of the longest consecutive sequence: 4
'

 



answered Aug 18, 2025 by avibootz

Related questions

...