go Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/go/ 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 go Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/go/ 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
Sort a slice of Int in Ascending and Descending order in Go (Golang) https://vikasboss.github.io/sort-slice-asc-desc-golang/ https://vikasboss.github.io/sort-slice-asc-desc-golang/#respond Thu, 13 Oct 2022 17:13:49 +0000 https://vikasboss.github.io/?p=9648 Sort a slice in Ascending order sort.Ints package of going can be used to sort a full slice or a part of the slice. It is going to sort the string into...

The post Sort a slice of Int in Ascending and Descending order in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Sort a slice in Ascending order

sort.Ints package of going can be used to sort a full slice or a part of the slice. It is going to sort the string into Ascending order.

Below is the signature of the method

https://pkg.go.dev/sort#Ints

func Ints(x []int)

It takes a slice ‘x’ as an argument and sorts the slice ‘x’ in place.

Below is the program for the same

package main

import (
	"fmt"
	"sort"
)

func main() {

	nums := []int{3, 4, 2, 1}
	fmt.Printf("Before: %v", nums)
	sort.Ints(nums)
	fmt.Printf("\nAfter: %v", nums)
}

Output

Before: [3 4 2 1]
After: [1 2 3 4]

Sort a slice in Descending order

To sort a slice in descending order we will use Slice method of sort pacakge

https://pkg.go.dev/sort#Slice

Below is the signature of the method

func Slice(x any, less func(i, j int) bool)

So this function takes two arguments

  • less func(i, j int) – This function is nothing but a comparator function

We can use this comparator function to decide the descending order of the elements in the slice. Below is an example

package main

import (
	"fmt"
	"sort"
)

func main() {

	nums := []int{3, 4, 2, 1}
	fmt.Printf("Before: %v", nums)
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] > nums[j]
	})
	fmt.Printf("\nAfter: %v", nums)
}

Output

Before: [3 4 2 1]
After: [4 3 2 1]

As a matter of fact, you can use sort.Slice method to also sort a slice in descending order. Below is an example

package main

import (
	"fmt"
	"sort"
)

func main() {

	nums := []int{3, 4, 2, 1}
	fmt.Printf("Before: %v", nums)
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] < nums[j]
	})
	fmt.Printf("\nAfter: %v", nums)
}

Output

Before: [3 4 2 1]
After: [1 2 3 4]

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 Sort a slice of Int in Ascending and Descending order in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/sort-slice-asc-desc-golang/feed/ 0 9648
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
Print the next or previous character given a char in Go (Golang) https://vikasboss.github.io/next-previous-char-golang/ https://vikasboss.github.io/next-previous-char-golang/#respond Sun, 09 Oct 2022 17:09:11 +0000 https://vikasboss.github.io/?p=9597 Overview Simply by doing plus 1 and minus 1 we can get the next and previous character given a current char. Program Here is the program for the same Output: Note: Check...

The post Print the next or previous character given a char in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

Simply by doing plus 1 and minus 1 we can get the next and previous character given a current char.

Program

Here is the program for the same

package main

import "fmt"

func main() {
	var curr byte
	curr = 'b'

	fmt.Println(string(curr + 1))
	fmt.Println(string(curr - 1))
}

Output:

c
a

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 Print the next or previous character given a char in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/next-previous-char-golang/feed/ 0 9597
Program for Longest Word in Dictionary through Deleting in Go (Golang) https://vikasboss.github.io/longest-word-dictionary-go/ https://vikasboss.github.io/longest-word-dictionary-go/#respond Fri, 30 Sep 2022 17:56:27 +0000 https://vikasboss.github.io/?p=9373 Overview A string and a dictionary of words are given. The objective is to find the longest word in the dictionary which is present as a subsequence in the given string. If the...

The post Program for Longest Word in Dictionary through Deleting in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

A string and a dictionary of words are given. The objective is to find the longest word in the dictionary which is present as a subsequence in the given string. If the number of possible results is more than 1 then return the longest word with the smallest lexicographical order.

Example 1

s = "mbacnago", dictionary = ["ale","mango","monkey","plea"]
Output: "mango"

Example 2

s = "mbacnago", dictionary = ["ba","ag"]
Output: "ag"

Program

Below is the program for the same

package main

import (
	"fmt"
	"sort"
)

func findLongestWord(s string, dictionary []string) string {
	sort.Slice(dictionary, func(i, j int) bool {
		lenI := len(dictionary[i])
		lenJ := len(dictionary[j])

		if lenI == lenJ {
			return dictionary[i] < dictionary[j]
		}

		return lenI > lenJ
	})

	lenS := len(s)

	for i := 0; i < len(dictionary); i++ {
		if isSubstring(s, dictionary[i], lenS) {
			return dictionary[i]
		}
	}

	return ""
}

func isSubstring(s string, sub string, lenS int) bool {
	lenSub := len(sub)

	if lenSub == 0 {
		return true
	}

	if lenSub > lenS {
		return false
	}

	for i, j := 0, 0; i < lenS && j < lenSub; {
		if i+lenSub-j-1 >= lenS {
			return false
		}
		if s[i] == sub[j] {
			j++
		}
		if j == lenSub {
			return true
		}
		i++
	}

	return false
}

func main() {
	output := findLongestWord("mbacnago", []string{"ale", "mango", "monkey", "plea"})
	fmt.Println(output)

	output = findLongestWord("mbacnago", []string{"ba", "ag"})
	fmt.Println(output)

}

Output

mango
ag

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 Longest Word in Dictionary through Deleting in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/longest-word-dictionary-go/feed/ 0 9373
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
Count unguarded cells program in Go (Golang) https://vikasboss.github.io/count-unguarded-cells-golang/ https://vikasboss.github.io/count-unguarded-cells-golang/#respond Thu, 25 Aug 2022 17:03:21 +0000 https://vikasboss.github.io/?p=8649 Overview Two integers m and n are given which represent an m*n grid. Other than that two 2D integer arrays are also given guards where guards[i] = [rowi , columni]. It represents...

The post Count unguarded cells program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

Two integers m and n are given which represent an m*n grid. Other than that two 2D integer arrays are also given

  • guards where guards[i] = [rowi , columni]. It represents the position of the ith guard
  • walls where guards[j] = [rowi , columni]. It represents the position of the ith wall

A guard can see in all the directions

  • North
  • South
  • East
  • West

unless obstructed by the wall. All the cells that the guard can see are counted as guarded. The objective is to find the number of unguarded cells

Here is the leetcode link for the same – https://leetcode.com/problems/count-unguarded-cells-in-the-grid/

Program

Below is the program for the same

package main

import "fmt"

func countUnguarded(m int, n int, guards [][]int, walls [][]int) int {

	occupancy := make([][]int, m)

	for i := 0; i < m; i++ {
		occupancy[i] = make([]int, n)
	}

	for _, val := range guards {
		i := val[0]
		j := val[1]
		occupancy[i][j] = 2
	}

	for _, val := range walls {
		i := val[0]
		j := val[1]
		occupancy[i][j] = -1
	}

	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if occupancy[i][j] == 2 {
				countUtil(i, j, m, n, &occupancy)
			}

		}
	}

	count := 0
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if occupancy[i][j] == 0 {
				count += 1
			}

		}
	}

	return count
}

func countUtil(x, y, m, n int, occupancy *([][]int)) {

	for i := x + 1; i < m; i++ {
		if (*occupancy)[i][y] == 0 {
			(*occupancy)[i][y] = 1
		}

		if (*occupancy)[i][y] == -1 || (*occupancy)[i][y] == 2 {
			break
		}
	}

	for i := x - 1; i >= 0; i-- {
		if (*occupancy)[i][y] == 0 {
			(*occupancy)[i][y] = 1
		}

		if (*occupancy)[i][y] == -1 || (*occupancy)[i][y] == 2 {
			break
		}
	}

	for i := y + 1; i < n; i++ {
		if (*occupancy)[x][i] == 0 {
			(*occupancy)[x][i] = 1
		}

		if (*occupancy)[x][i] == -1 || (*occupancy)[x][i] == 2 {
			break
		}
	}

	for i := y - 1; i >= 0; i-- {

		if (*occupancy)[x][i] == 0 {
			(*occupancy)[x][i] = 1
		}

		if (*occupancy)[x][i] == -1 || (*occupancy)[x][i] == 2 {
			break
		}
	}

}

func main() {
	output := countUnguarded(4, 6, [][]int{{0, 0}, {1, 1}, {2, 3}}, [][]int{{0, 1}, {2, 2}, {1, 4}})
	fmt.Println(output)

	output = countUnguarded(3, 3, [][]int{{1, 1}}, [][]int{{0, 1}, {1, 0}, {2, 1}, {1, 2}})
	fmt.Println(output)
}

Output

7
4

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 Count unguarded cells program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/count-unguarded-cells-golang/feed/ 0 8649
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
Is Graph Bipartite Program in Go (Golang) https://vikasboss.github.io/graph-bipartite-golang/ https://vikasboss.github.io/graph-bipartite-golang/#respond Mon, 01 Aug 2022 05:28:36 +0000 https://vikasboss.github.io/?p=8321 Overview An undirected graph is given. A  graph is said to be bipartite if the nodes of the graph can be partitioned into two subsets such that every edge connects one node...

The post Is Graph Bipartite Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

An undirected graph is given. A  graph is said to be bipartite if the nodes of the graph can be partitioned into two subsets such that every edge connects one node in the first subset to some other node in the second subset.

The graph contains n nodes numbered from 0 to n-1. Input is a matrix named graph which is a 2D  matrix where graph[i] contains the node to which ith node is connected. For eg if

graph[0] = [1,3]

this means node 0 is connected to node 1 and node 3

Example 1

Input: [[1,3],[0,2],[1,3],[0,2]]
Output: true

Example 2

Input: [[1,4],[0,2],[1,3],[2,4],[0,3]
Output: false

Idea is to use DFS  here. We will try to assign either red or black color to each of the nodes. If a node is colored red then its neighbors must be colored black.

  • We are able to color  in this  way then the graph is bipartite
  • If while coloring we  find  that two nodes connected by  an edge have the same color then the graph is not bipartite

Let’s see the program for the same

Program

Below is the program for the same

package main

import "fmt"

func isBipartite(graph [][]int) bool {
	nodeMap := make(map[int][]int)

	numNodes := len(graph)

	if numNodes == 1 {
		return true
	}
	for i := 0; i < numNodes; i++ {
		nodes := graph[i]
		for j := 0; j < len(nodes); j++ {
			nodeMap[i] = append(nodeMap[i], nodes[j])
		}
	}

	color := make(map[int]int)

	for i := 0; i < numNodes; i++ {
		if color[i] == 0 {
			color[i] = 1
			isBiPartite := visit(i, nodeMap, &color)
			if !isBiPartite {
				return false
			}
		}
	}

	return true

}

func visit(source int, nodeMap map[int][]int, color *map[int]int) bool {

	for _, neighbour := range nodeMap[source] {
		if (*color)[neighbour] == 0 {
			if (*color)[source] == 1 {
				(*color)[neighbour] = 2
			} else {
				(*color)[neighbour] = 1
			}
			isBipartite := visit(neighbour, nodeMap, color)
			if !isBipartite {
				return false
			}
		} else {
			if (*color)[source] == (*color)[neighbour] {
				return false
			}
		}
	}

	return true
}

func main() {
	output := isBipartite([][]int{{1, 3}, {0, 2}, {1, 3}, {0, 2}})
	fmt.Println(output)

	output = isBipartite([][]int{{1, 4}, {0, 2}, {1, 3}, {2, 4}, {0, 3}})
	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 Is Graph Bipartite Program in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/graph-bipartite-golang/feed/ 0 8321