Golang
Golang

 

Go Program


package main

import (
    "fmt"
    "sort"
)

// longestConsecutive finds the length of the longest consecutive elements sequence in the array.
func longestConsecutive(nums []int) int {
    if len(nums) == 0 {
        return 0
    }

    // Remove duplicates and sort the array
    numSet := make(map[int]struct{})
    for _, num := range nums {
        numSet[num] = struct{}{}
    }

    // Convert map keys to a slice and sort it
    uniqueNums := make([]int, 0, len(numSet))
    for num := range numSet {
        uniqueNums = append(uniqueNums, num)
    }
    sort.Ints(uniqueNums)

    longestStreak := 1
    currentStreak := 1

    // Iterate through the sorted array to find the longest streak
    for i := 1; i < len(uniqueNums); i++ { if uniqueNums[i] == uniqueNums[i-1]+1 { currentStreak++ } else { if currentStreak > longestStreak {
                longestStreak = currentStreak
            }
            currentStreak = 1
        }
    }

    // Check at the end of the loop
    return max(longestStreak, currentStreak)
}

// max returns the maximum of two integers.
func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func main() {
    nums := []int{100, 4, 200, 1, 3, 2}
    result := longestConsecutive(nums)
    fmt.Printf("The length of the longest consecutive sequence is: %d\n", result)
}

Program Explanation

The program consists of several components that work together to find the longest consecutive sequence of numbers in an array:

  • Package Declaration: The program begins with the declaration of the main package, which is standard for Go programs.
  • Imports: The fmt package is imported for formatted I/O, and sort is used to sort the unique numbers.
  • Function longestConsecutive: This function takes an array of integers and returns the length of the longest consecutive sequence.
  • Handling Duplicates: A map is used to store unique numbers, removing duplicates efficiently.
  • Sorting: The unique numbers are sorted to facilitate finding consecutive sequences.
  • Finding Consecutive Sequences: A loop iterates through the sorted numbers, tracking the current streak of consecutive numbers and updating the longest streak as necessary.
  • Helper Function max: This function returns the maximum of two integers and is used to ensure the longest streak is returned correctly.
  • Main Function: The main function initializes an array of integers, calls the longestConsecutive function, and prints the result.

How to Run the Program

  1. Install Go on your machine if you haven’t already.
  2. Create a new file named longest_sequence.go.
  3. Copy and paste the program code into the file.
  4. Open a terminal and navigate to the directory containing the file.
  5. Run the program using the command: go run longest_sequence.go.

Conclusion

This Go program effectively identifies the longest consecutive sequence in an array by utilizing maps for uniqueness and sorting. This approach ensures efficiency while maintaining clarity in the implementation.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)