0% found this document useful (0 votes)
41 views1 page

Complete Golang Problems Solutions

Uploaded by

Manohar Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views1 page

Complete Golang Problems Solutions

Uploaded by

Manohar Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Golang Problem Set with Solutions

1. Two Sum
func twoSum(nums []int, target int) []int { lookup := make(map[int]int) for i, num
:= range nums { if j, ok := lookup[target - num]; ok { return []int{j,
i} } lookup[num] = i } return nil }

2. Valid Anagram
func isAnagram(s string, t string) bool { if len(s) != len(t) { return false
} count := make(map[rune]int) for _, ch := range s { count[ch]++ }
for _, ch := range t { count[ch]-- if count[ch] < 0 { return
false } } return true }

3. Climbing Stairs (DP)


func climbStairs(n int) int { if n <= 2 { return n } dp := make([]int,
n+1) dp[1], dp[2] = 1, 2 for i := 3; i <= n; i++ { dp[i] = dp[i-1] +
dp[i-2] } return dp[n] }

4. Maximum Depth of Binary Tree


type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func
maxDepth(root *TreeNode) int { if root == nil { return 0 } leftDepth
:= maxDepth([Link]) rightDepth := maxDepth([Link]) if leftDepth >
rightDepth { return leftDepth + 1 } return rightDepth + 1 }

5. Number of Islands (DFS)


func numIslands(grid [][]byte) int { count := 0 for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ { if grid[i][j] == '1' {
dfs(grid, i, j) count++ } } } return count }
func dfs(grid [][]byte, i, j int) { if i < 0 || i >= len(grid) || j < 0 || j >=
len(grid[0]) || grid[i][j] != '1' { return } grid[i][j] = '0'
dfs(grid, i+1, j) dfs(grid, i-1, j) dfs(grid, i, j+1) dfs(grid, i, j-1) }

6. REST API Handler (Golang net/http)


import ( "fmt" "net/http" ) func helloHandler(w [Link], r
*[Link]) { [Link](w, "Hello, world!") } func main() {
[Link]("/hello", helloHandler) [Link](":8080", nil) }

7. Goroutine and Channel (Worker Example)


import ( "fmt" "time" ) func worker(id int, jobs <-chan int, results chan<- int)
{ for j := range jobs { [Link]("Worker %d started job %d\n", id, j)
[Link]([Link]) [Link]("Worker %d finished job %d\n", id, j)
results <- j * 2 } } func main() { jobs := make(chan int, 5) results :=
make(chan int, 5) for w := 1; w <= 3; w++ { go worker(w, jobs, results) }
for j := 1; j <= 5; j++ { jobs <- j } close(jobs) for a := 1; a <= 5;
a++ { <-results } }

You might also like