golang Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/golang/ Fri, 10 Feb 2023 14:56:06 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 golang Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/golang/ 32 32 159787465 Check if a string contains single or multiple whitespaces in Go (Golang) https://vikasboss.github.io/string-whitespace-golang/ https://vikasboss.github.io/string-whitespace-golang/#respond Fri, 10 Feb 2023 14:55:10 +0000 https://vikasboss.github.io/?p=10985 Overview A simple regex can be used to check if a string contains single or multiple white spaces in Go. Here is the program for the same Program Output Note: Check out...

The post Check if a string contains single or multiple whitespaces in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

A simple regex can be used to check if a string contains single or multiple white spaces in Go.

Here is the program for the same

Program

package main

import (
	"fmt"
	"regexp"
)

func main() {
	//Single whitespace
	sampleWord := "Good morning"

	isWhitespacePresent := regexp.MustCompile(`\s`).MatchString(sampleWord)
	fmt.Println(isWhitespacePresent)

	//Multiple Whitespace
	sampleWord = "Good   morning"
	isMultipleWhitespacePresent := regexp.MustCompile(`\s*`).MatchString(sampleWord)
	fmt.Println(isMultipleWhitespacePresent)
}

Output

true
true

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you –

All Design Patterns Golang

Note: Check out our system design tutorial series System Design Questions

The post Check if a string contains single or multiple whitespaces in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/string-whitespace-golang/feed/ 0 10985
Repeat a string multiple times in Go (Golang) https://vikasboss.github.io/repeat-string-golang/ https://vikasboss.github.io/repeat-string-golang/#respond Sun, 09 Oct 2022 17:12:09 +0000 https://vikasboss.github.io/?p=9601 Overview strings.Repeat method can be used to repeat a string multiple times in Go (Golang) Here is the link to this function in the Go strings package https://pkg.go.dev/strings#Repeat Here is the signature...

The post Repeat a string multiple times in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

strings.Repeat method can be used to repeat a string multiple times in Go (Golang)

Here is the link to this function in the Go strings package

https://pkg.go.dev/strings#Repeat

Here is the signature of the method

func Repeat(s string, count int) string

The first argument is the original string and count is the number of times the strings needs to be repeated

Program

Here is the program for the same

package main

import (
	"fmt"
	"strings"
)

func main() {
	copy := strings.Repeat("a", 2)
	fmt.Println(copy)

	copy = strings.Repeat("abc", 3)
	fmt.Println(copy)
}

Output:

aa
abcabcabc

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you –All Design Patterns Golang

The post Repeat a string multiple times in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/repeat-string-golang/feed/ 0 9601
Remove Linked List Elements Program in Go (Golang) https://vikasboss.github.io/remove-linked-list-elements-golang/ https://vikasboss.github.io/remove-linked-list-elements-golang/#respond Thu, 15 Sep 2022 14:40:30 +0000 https://vikasboss.github.io/?p=9016 Overview Given a linked list and a value, delete all nodes from the linked list whose value is equal to the given value. Example 1 Example 2 Program Below is the program...

The post Remove Linked List Elements Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

Given a linked list and a value, delete all nodes from the linked list whose value is equal to the given value.

Example 1

Input: [1, 2, 1, 3, 6], 1
Output: [2, 3, 6]

Example 2

Input: [2, 2, 3], 2
Output: [3]

Program

Below is the program for the same

package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

type SingleList struct {
	Len  int
	Head *ListNode
}

func (s *SingleList) AddFront(num int) *ListNode {
	ele := &ListNode{
		Val: num,
	}
	if s.Head == nil {
		s.Head = ele
	} else {
		ele.Next = s.Head
		s.Head = ele
	}
	s.Len++
	return ele
}
func removeElements(head *ListNode, val int) *ListNode {
	var prev *ListNode

	curr := head

	for curr != nil {
		if curr.Val == val {
			if prev == nil {
				head = curr.Next
			} else {
				prev.Next = curr.Next
			}
		} else {
			prev = curr
		}
		curr = curr.Next

	}

	return head
}

func main() {
	first := initList()
	first.AddFront(6)
	first.AddFront(3)
	first.AddFront(1)
	first.AddFront(2)
	first.AddFront(1)

	result := removeElements(first.Head, 1)
	fmt.Println("Resultant First List")
	result.Traverse()

	first = initList()
	first.AddFront(3)
	first.AddFront(2)
	first.AddFront(2)

	fmt.Println("\nResultant Second List")
	result = removeElements(first.Head, 2)
	result.Traverse()

}

func initList() *SingleList {
	return &SingleList{}
}

func (l *ListNode) Traverse() {
	for l != nil {
		fmt.Println(l.Val)
		l = l.Next
	}
}

Output

Resultant First List
2
3
6

Resultant Second List
3

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you – All Design Patterns Golang

Also, check out our system design tutorial series here – System Design Tutorial Series

The post Remove Linked List Elements Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/remove-linked-list-elements-golang/feed/ 0 9016
Recover Binary Search Tree Program in Go (Golang) https://vikasboss.github.io/recover-binary-search-tree-golang/ https://vikasboss.github.io/recover-binary-search-tree-golang/#respond Fri, 19 Aug 2022 17:16:58 +0000 https://vikasboss.github.io/?p=8554 Overview The root of a binary search tree is given. Two nodes of the binary search tree have been swapped. We need to fix the binary tree and recover the original structure...

The post Recover Binary Search Tree Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

The root of a binary search tree is given. Two nodes of the binary search tree have been swapped. We need to fix the binary tree and recover the original structure

Program

Below is the program for the same

package main

import "fmt"

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func recoverTree(root *TreeNode) {
	var prev *TreeNode
	var first *TreeNode
	var mid *TreeNode
	var last *TreeNode

	recoverTreeUtil(root, &prev, &first, &mid, &last)

	if first != nil && last != nil {
		first.Val, last.Val = last.Val, first.Val
	} else if first != nil && mid != nil {
		first.Val, mid.Val = mid.Val, first.Val
	}
}

func recoverTreeUtil(root *TreeNode, prev, first, mid, last **TreeNode) {
	if root == nil {
		return
	}

	recoverTreeUtil(root.Left, prev, first, mid, last)

	if *prev == nil {
		*prev = root
	} else if *first == nil && (*prev).Val > root.Val {
		*first = *prev
		*mid = root
	} else if (*prev).Val > root.Val {
		*last = root
	}

	*prev = root

	recoverTreeUtil(root.Right, prev, first, mid, last)
}

func main() {
	root := TreeNode{Val: 2}
	root.Left = &TreeNode{Val: 3}
	root.Right = &TreeNode{Val: 1}

	recoverTree(&root)
	fmt.Println(root.Val)
	fmt.Println(root.Left.Val)
	fmt.Println(root.Right.Val)

}

Output

2
1
3

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you – All Design Patterns Golang

Also, check out our system design tutorial series here – System Design Tutorial Series

The post Recover Binary Search Tree Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/recover-binary-search-tree-golang/feed/ 0 8554
Program for ugly number 2 in Go (Golang) https://vikasboss.github.io/program-for-ugly-number-2-in-go-golang/ https://vikasboss.github.io/program-for-ugly-number-2-in-go-golang/#respond Sat, 13 Aug 2022 12:05:15 +0000 https://vikasboss.github.io/?p=8491 Overview An ugly number is a number whose prime factors are limited to 2,3 and 5. We have already seen a program where given a number n returns true if it is...

The post Program for ugly number 2 in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

An ugly number is a number whose prime factors are limited to 2,3 and 5. We have already seen a program where given a number n returns true if it is an ugly number otherwise returns false. Below is the link to that program https://vikasboss.github.io/ugly-number-golang/

In this tutorial, we will write a program where given a number n, find the nth ugly number

Example 1

Input: 5
Output: 5
Reason: First five ugly numbers are 1, 2, 3, 4, 5 hence 5th ugly number is 5

Example 2

Input: 20
Output: 36

The idea is to use dynamic programming here. We will keep track of multiple of 2, 3, and 5. The next ugly number will always be the minimum of these three.

Program

Below is the program for the same

package main

import "fmt"

func nthUglyNumber(n int) int {
	dpUgly := make([]int, n)

	dpUgly[0] = 1

	next_multiple_of_2 := 2
	next_multiple_of_3 := 3
	next_multiple_of_5 := 5

	i2 := 0
	i3 := 0
	i5 := 0

	for i := 1; i < n; i++ {
		nextUglyNumber := minOfThree(next_multiple_of_2, next_multiple_of_3, next_multiple_of_5)
		dpUgly[i] = nextUglyNumber

		if nextUglyNumber == next_multiple_of_2 {
			i2++
			next_multiple_of_2 = 2 * dpUgly[i2]
		}

		if nextUglyNumber == next_multiple_of_3 {
			i3++
			next_multiple_of_3 = 3 * dpUgly[i3]
		}

		if nextUglyNumber == next_multiple_of_5 {
			i5++
			next_multiple_of_5 = 5 * dpUgly[i5]
		}

	}

	return dpUgly[n-1]

}

func minOfThree(a, b, c int) int {
	if a < b && a < c {
		return a
	}

	if b < c {
		return b
	}

	return c
}

func main() {
	output := nthUglyNumber(5)
	fmt.Println(output)

	output = nthUglyNumber(20)
	fmt.Println(output)
}

Output

5
36

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang - Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you - All Design Patterns Golang

Also, check out our system design tutorial series here - System Design Tutorial Series

The post Program for ugly number 2 in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/program-for-ugly-number-2-in-go-golang/feed/ 0 8491
Binary Tree Maximum Path Sum Program in Go (Golang) https://vikasboss.github.io/binary-tree-maximum-path-sum-golang/ https://vikasboss.github.io/binary-tree-maximum-path-sum-golang/#respond Sat, 30 Jul 2022 04:04:26 +0000 https://vikasboss.github.io/?p=8286 Overview A  binary tree is given. The objective is to find the maximum Path Sum in that binary tree.  A path in a binary tree is a sequence of nodes that are connected...

The post Binary Tree Maximum Path Sum Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

A  binary tree is given. The objective is to find the maximum Path Sum in that binary tree.  A path in a binary tree is a sequence of nodes that are connected to each other. Each node only appears once in the Maximum Path Sum

Example 1

Output: 16
Maximum Sum Path is: 4->2->1->3->6

Example 2

Output: 14
Maximum Sum Path is: 5->3->6

The idea is to track below four  values at every node

  • a = root.Val
  • b = root.Val + leftSubTreeMaxSum
  • c  = root.Val + rightSubTreeMaxSum
  • d =  root.Val + leftSubTreeMaxSum+  rightSubTreeMaxSum

Then

  • Max sum at a given node is given max of (a,b,c,d)
  • The return value in the recursive call would be a max of (a,b,c).  Why? This is because only the path of a or b or c represents a path that can be taken into account at the parent node. d cannot be taken into account because it becomes an invalid path. To understand this with an example consider the binary tree in example two above. Path 5->3->6 cannot include parent node -5 in its path because it becomes an invalid path.

Program

Below is the program for the same

package main

import (
	"fmt"
	"math"
)

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func maxPathSum(root *TreeNode) int {
	res := math.MinInt64

	maxPathSumUtil(root, &res)
	return res
}

func maxPathSumUtil(root *TreeNode, res *int) int {
	if root == nil {
		return 0
	}

	l := maxPathSumUtil(root.Left, res)
	r := maxPathSumUtil(root.Right, res)

	a := root.Val
	b := root.Val + l
	c := root.Val + r
	d := root.Val + l + r

	maxReturnSum := maxOfThree(a, b, c)

	maxSumPath := maxOfTwo(maxReturnSum, d)
	if maxSumPath > *res {
		*res = maxSumPath
	}

	return maxReturnSum
}

func maxOfThree(a, b, c int) int {
	if a > b && a > c {
		return a
	}

	if b > c {
		return b
	}

	return c
}

func maxOfTwo(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Left.Left = &TreeNode{Val: 4}
	root.Right = &TreeNode{Val: 3}
	root.Right.Left = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}

	output := maxPathSum(root)
	fmt.Println(output)

	root = &TreeNode{Val: -10}
	root.Left = &TreeNode{Val: 2}
	root.Left.Left = &TreeNode{Val: 4}
	root.Right = &TreeNode{Val: 3}
	root.Right.Left = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	output = maxPathSum(root)
	fmt.Println(output)

}

Output:

16
14

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you – All Design Patterns Golang

Also, check out our system design tutorial series here – System Design Tutorial Series

The post Binary Tree Maximum Path Sum Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/binary-tree-maximum-path-sum-golang/feed/ 0 8286
Sort characters by frequency in Go (Golang) https://vikasboss.github.io/sort-characters-frequency-go/ https://vikasboss.github.io/sort-characters-frequency-go/#respond Thu, 28 Jul 2022 16:23:13 +0000 https://vikasboss.github.io/?p=8252 Overview An input string is given. The objective is to sort the string based on frequency. We have to sort based on decreasing order of the frequency of characters. Let’s understand it...

The post Sort characters by frequency in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

An input string is given. The objective is to sort the string based on frequency. We have to sort based on decreasing order of the frequency of characters. Let’s understand it with an example

Example 1

Input: "bcabcb"
Output: "bbbcca"

Example 2

Input: "mniff"
Output: "ffmni"

Program

Below is the program for the same

package main

import (
	"fmt"
	"sort"
)

func frequencySort(s string) string {
	stringMap := make(map[byte]int)
	lenS := len(s)
	for i := 0; i < lenS; i++ {
		stringMap[s[i]]++
	}

	itemArray := make([]item, 0)

	for key, value := range stringMap {
		i := item{
			char:      key,
			frequency: value,
		}
		itemArray = append(itemArray, i)
	}

	sort.Slice(itemArray, func(i, j int) bool {
		return itemArray[i].frequency > itemArray[j].frequency
	})

	output := ""

	for i := 0; i < len(itemArray); i++ {
		for j := 0; j < itemArray[i].frequency; j++ {
			output = output + string(itemArray[i].char)
		}
	}

	return output

}

type item struct {
	char      byte
	frequency int
}

func main() {
	output := frequencySort("bcabcb")
	fmt.Println(output)

	output = frequencySort("mniff")
	fmt.Println(output)

}

Output:

bbbcca
ffmni

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang - Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you - All Design Patterns Golang

Also, check out our system design tutorial series here - System Design Tutorial Series

The post Sort characters by frequency in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/sort-characters-frequency-go/feed/ 0 8252
Check If N and Its Double Exist in Go (Golang) https://vikasboss.github.io/number-double-golang/ https://vikasboss.github.io/number-double-golang/#respond Mon, 25 Jul 2022 16:56:54 +0000 https://vikasboss.github.io/?p=8209 Overview An array is given. The objective is to find if there exists any number for which it’s double also exists. Example 1 Example 2 The idea is to use a map...

The post Check If N and Its Double Exist in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

An array is given. The objective is to find if there exists any number for which it’s double also exists.

Example 1

Input: [8,5,4,3]
Output: true
Explanation: 4 and 8

Example 2

Input: [1,3,7,9]
Output: false
Explanation: There exists no number for which its double exist

The idea is to use a map here. For every element, we will check  and return true if

  • If its double exists in the map
  • If the number is even then if its half exists in the map

Program

Below is the program for the same

package main

import "fmt"

func checkIfExist(arr []int) bool {
	numMap := make(map[int]bool)

	for i := 0; i < len(arr); i++ {
		if numMap[arr[i]*2] {
			return true
		}
		if arr[i]%2 == 0 && numMap[arr[i]/2] {
			return true
		}
		numMap[arr[i]] = true
	}
	return false
}

func main() {
	output := checkIfExist([]int{8, 5, 4, 3})
	fmt.Println(output)

	output = checkIfExist([]int{1, 3, 7, 9})
	fmt.Println(output)

}

Output:

true
false

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang - Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you - All Design Patterns Golang

Also, check out our system design tutorial series here - System Design Tutorial Series

The post Check If N and Its Double Exist in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/number-double-golang/feed/ 0 8209
Program for Pascal’s Triangle in Go (Golang) https://vikasboss.github.io/program-pascal-triangle-golang/ https://vikasboss.github.io/program-pascal-triangle-golang/#respond Mon, 25 Jul 2022 11:40:31 +0000 https://vikasboss.github.io/?p=8206 Overview The objective is to find the print n number of rows of Pascal’s triangle. The number n is given as an input to the program Example 1 Example 2 Refer to...

The post Program for Pascal’s Triangle in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

The objective is to find the print n number of rows of Pascal’s triangle. The number n is given as an input to the program

Example 1

Input: numRows = 4
Output: [[1],[1,1],[1,2,1],[1,3,3,1]]

Example 2

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Refer to this link to know more about Pascal’s Triangle here – https://en.wikipedia.org/wiki/Pascal%27s_triangle

The idea is to use dynamic programming here.

Program

Below is the program for the same

package main

import "fmt"

func generate(numRows int) [][]int {
	firstRow := []int{1}

	if numRows == 1 {
		return [][]int{firstRow}
	}

	secondRow := []int{1, 1}

	if numRows == 2 {
		return [][]int{firstRow, secondRow}
	}

	output := [][]int{firstRow, secondRow}

	for i := 2; i < numRows; i++ {
		temp := make([]int, i+1)

		lastRow := output[i-1]

		temp[0] = 1
		temp[i] = 1

		for j := 1; j < i; j++ {
			temp[j] = lastRow[j-1] + lastRow[j]
		}

		output = append(output, temp)

	}

	return output

}

func main() {
	output := generate(4)
	fmt.Println(output)

	output = generate(5)
	fmt.Println(output)
}

Output:

[1] [1 1] [1 2 1] [1 3 3 1]]
[[1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]]

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang - Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you - All Design Patterns Golang

Also, check out our system design tutorial series here - System Design Tutorial Series

The post Program for Pascal’s Triangle in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/program-pascal-triangle-golang/feed/ 0 8206
Longest Consecutive Sequence Program in Go (Golang) https://vikasboss.github.io/longest-consecutive-sequence-golang/ https://vikasboss.github.io/longest-consecutive-sequence-golang/#respond Thu, 21 Jul 2022 16:02:51 +0000 https://vikasboss.github.io/?p=8152 Overview An integer array is given. Find the length of the longest consecutive sequence in it. Let’s see an example to understand it Example 1 Example 2 The naive idea is to...

The post Longest Consecutive Sequence Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

An integer array is given. Find the length of the longest consecutive sequence in it. Let’s see an example to understand it

Example 1

Input: [4,7,3,8,2,1]
Output: 4
Reason: The longest consecutive sequence is [1,2,3,4]

Example 2

Input: [4,7,3,8,2,1,9,24,10,11]
Output: 5
Reason: The longest consecutive sequence is [7,8,9,10,11]

The naive idea is to sort the array and return the longest consecutive sequence. But we can do this in O(n) time. Idea is to use a hash here. Below is the idea

  • Store each of the numbers in the hash.
  • Then starting with each number, find the length of the longest consecutive sequence beginning at that number. So if a number let’s say is n. We try to find n+1, n+2… in the hash and get the length of the longest consecutive sequence  starting from that number
  • If the length find in step 2 is greater than the previous longest consecutive sequence found, then update the longest consecutive sequence length

Program

Below is the program for the same

package main

import "fmt"

func longestConsecutive(nums []int) int {
	numsMap := make(map[int]int)

	lenNums := len(nums)

	for i := 0; i < lenNums; i++ {
		numsMap[nums[i]] = 0
	}

	maxLCS := 0
	for i := 0; i < lenNums; i++ {
		currentLen := 1
		counter := 1

		for {
			val, ok := numsMap[nums[i]+counter]
			if ok {
				if val != 0 {
					currentLen += val
					break
				} else {
					currentLen += 1
					counter += 1
				}
			} else {
				break
			}
		}

		if currentLen > maxLCS {
			maxLCS = currentLen
		}
		numsMap[nums[i]] = currentLen
	}

	return maxLCS
}

func main() {
	output := longestConsecutive([]int{4, 7, 3, 8, 2, 1})
	fmt.Println(output)

	output = longestConsecutive([]int{4, 7, 3, 8, 2, 1, 9, 24, 10, 11})
	fmt.Println(output)

}

Output:

4
5

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you – All Design Patterns Golang

Also, check out our system design tutorial series here – System Design Tutorial Series

The post Longest Consecutive Sequence Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/longest-consecutive-sequence-golang/feed/ 0 8152