This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Go

Go projects

1 - Leetcode submissions

1.1 - 2024-05-04 15:08:36 +0000 UTC

Boats to Save People

Code

func numRescueBoats(people []int, limit int) int {
    sort.Ints(people)

    numberOfBouts := 0

    start := 0
    end := len(people)-1

    for start < end {
        if people[start] + people[end] <= limit {
            numberOfBouts++
            start++
        }else{
            numberOfBouts++
        }
        end--
    }

    if start == end {
        numberOfBouts++
    }

    return numberOfBouts
}

1.2 - 2024-05-03 14:41:51 +0000 UTC

Compare Version Numbers

Code

func compareVersion(version1 string, version2 string) int {

	rev1 := strings.Split(version1, ".")
	rev2 := strings.Split(version2, ".")
    // fmt.Println(rev1, rev2)

	revInt1 := make([]int, len(rev1))
	revInt2 := make([]int, len(rev2))

	for i := 0; i < len(rev1); i++ {
		revInt1[i], _ = strconv.Atoi(rev1[i])
	}
	for i := 0; i < len(rev2); i++ {
		revInt2[i], _ = strconv.Atoi(rev2[i])
	}
    // fmt.Println(revInt1, revInt2)

	i := 0
	j := 0

	for i < len(revInt1) && j < len(revInt2) {

		if revInt1[i] < revInt2[j] {
			return -1
		} else if revInt1[i] > revInt2[j] {
			return 1
		}
		i++
		j++
	}

	for i < len(revInt1) {
		if revInt1[i] > 0 {
			return 1
		}
		i++
	}
	for j < len(revInt2) {
		if revInt2[j] > 0 {
			return -1
		}
		j++
	}
	return 0
}

1.3 - 2024-05-02 16:49:20 +0000 UTC

Largest Positive Integer That Exists With Its Negative

Code

func findMaxK(nums []int) int {
    alreadySeenNums := map[int]bool{}
    res := -1

    for _, num := range nums {
        numAbs := int(math.Abs(float64(num)))

        if numAbs < res {
            continue
        }

        if alreadySeenNums[-num] {
            res = numAbs
        } else {
            alreadySeenNums[num] = true
        }
    }

    return res
}

1.4 - 2024-05-01 09:05:11 +0000 UTC

Find if Path Exists in Graph

Code

type UnionFind struct {
    parent []int
    rank   []int
}

func NewUnionFind(n int) *UnionFind {
    parent := make([]int, n)
    rank := make([]int, n)
    for i := 0; i < n; i++ {
        parent[i] = i
    }
    return &UnionFind{parent, rank}
}

func (uf *UnionFind) Find(u int) int {
    if uf.parent[u] != u {
        uf.parent[u] = uf.Find(uf.parent[u])
    }
    return uf.parent[u]
}

func (uf *UnionFind) UnionByRank(u, v int) {
    i := uf.Find(u)
    j := uf.Find(v)
    if i == j {
        return
    }
    if uf.rank[i] < uf.rank[j] {
        uf.parent[i] = j
    } else if uf.rank[i] > uf.rank[j] {
        uf.parent[j] = i
    } else {
        uf.parent[i] = j
        uf.rank[j]++
    }
}

func validPath(n int, edges [][]int, source int, destination int) bool {
    uf := NewUnionFind(n)
    for _, edge := range edges {
        u, v := edge[0], edge[1]
        uf.UnionByRank(u, v)
    }
    return uf.Find(source) == uf.Find(destination)
}

1.5 - 2024-05-01 09:04:46 +0000 UTC

Number of Wonderful Substrings

Code

func get(c rune) int {

    return int(c - 'a')

}



func wonderfulSubstrings(word string) int64 {

    cnt := make([]int64, 1024)

    cnt[0] = 1



    curState := 0

    res := int64(0)



    for _, c := range word {

        curState ^= 1 << get(c)



        res += cnt[curState]

        for odd := 'a'; odd <= 'j'; odd++ {

            oddState := curState ^ (1 << get(odd))

            res += cnt[oddState]

        }



        cnt[curState]++

    }



    return res

}

1.6 - 2024-05-01 09:04:24 +0000 UTC

Sum of Distances in Tree

Code


func sumOfDistancesInTree(n int, edges [][]int) []int {
	graph := make(map[int][]int)
	count := make([]int, n)
	res := make([]int, n)

	for _, edge := range edges {
		u, v := edge[0], edge[1]
		graph[u] = append(graph[u], v)
		graph[v] = append(graph[v], u)
	}

	var dfs1 func(cur, parent int)
	dfs1 = func(cur, parent int) {
		count[cur] = 1
		for _, child := range graph[cur] {
			if child != parent {
				dfs1(child, cur)
				count[cur] += count[child]
				res[cur] += res[child] + count[child]
			}
		}
	}

	var dfs2 func(cur, parent int)
	dfs2 = func(cur, parent int) {
		for _, child := range graph[cur] {
			if child != parent {
				res[child] = res[cur] + n - 2*count[child]
				dfs2(child, cur)
			}
		}
	}

	dfs1(0, -1)
	dfs2(0, -1)

	return res
}

1.7 - 2024-05-01 09:02:52 +0000 UTC

Reverse Prefix of Word

Code

func reversePrefix(word string, ch byte) string {
    var natija string
    for i := 0; i < len(word); i++ {
        if word[i] == ch { 
            ch_index := i
            for i >= 0 {
                natija += string(word[i])
                i--
            } 
            return natija + word[ch_index + 1 : ]
        }
    }    
    return word
}

1.8 - 2024-04-29 18:04:33 +0000 UTC

Minimum Number of Operations to Make Array XOR Equal to K

Code

func minOperations(nums []int, k int) int {
    res := k
    for _, n := range nums {
        res ^= n
    }
    var ans int
    for res > 0 {
        ans += res%2
        res = res >> 1
    }
    return ans
}

1.9 - 2024-04-26 07:34:22 +0000 UTC

Minimum Falling Path Sum II

Code



type Triplet struct {
	minSum       int
	secondMinSum int
	minSumIndex  int
}

func minFallingPathSum(grid [][]int) int {
	return minFallingPathSumHelper(0, grid).minSum
}

func minFallingPathSumHelper(row int, grid [][]int) Triplet {
	if row == len(grid) {
		return Triplet{0, 0, 0}
	}

	nextRowTriplet := minFallingPathSumHelper(row+1, grid)
	currentTriplet := Triplet{math.MaxInt32, math.MaxInt32, -1}

	for col := 0; col < len(grid[0]); col++ {
		var value int
		if col != nextRowTriplet.minSumIndex {
			value = grid[row][col] + nextRowTriplet.minSum
		} else {
			value = grid[row][col] + nextRowTriplet.secondMinSum
		}

		if value <= currentTriplet.minSum {
			currentTriplet.secondMinSum = currentTriplet.minSum
			currentTriplet.minSum = value
			currentTriplet.minSumIndex = col
		} else if value < currentTriplet.secondMinSum {
			currentTriplet.secondMinSum = value
		}
	}

	return currentTriplet
}

1.10 - 2024-04-25 17:32:24 +0000 UTC

Longest Ideal Subsequence

Code

func longestIdealString(s string, k int) int {
	dp := make([]int, 27)
	n := len(s)

	for i := n - 1; i >= 0; i-- {
		cc := s[i]
		idx := int(cc - 'a')
		maxi := -1 << 31

		left := max(idx-k, 0)
		right := min(idx+k, 26)

		for j := left; j <= right; j++ {
			maxi = max(maxi, dp[j])
		}

		dp[idx] = maxi + 1
	}

	max := -1 << 31
	for _, val := range dp {
		if val > max {
			max = val
		}
	}

	return max
}

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

1.11 - 2024-04-24 12:06:12 +0000 UTC

N-th Tribonacci Number

Code

func tribonacci(n int) int {
	if n < 2 {
		return n
	}

	dp := []int{0, 1, 1}

	for i := 3; i <= n; i++ {
		next := dp[0] + dp[1] + dp[2]
		dp[0], dp[1], dp[2] = dp[1], dp[2], next
	}

	return dp[2]
}

1.12 - 2024-04-23 15:14:09 +0000 UTC

Minimum Height Trees

Code



func findMinHeightTrees(n int, edges [][]int) []int {
	counts := make([]int, n)
	links := make([]int, n)
	for _, edge := range edges {
		links[edge[0]] ^= edge[1]
		counts[edge[0]]++
		links[edge[1]] ^= edge[0]
		counts[edge[1]]++
	}
	Qu := make([]int, 0)
	dists := make([]int, n)
	for i := 0; i < n; i++ {
		if counts[i] == 1 {
			Qu = append(Qu, i)
		}
	}
	stp := 1
	for len(Qu) > 0 {
		size := len(Qu)
		for j := 0; j < size; j++ {
			tmp := Qu[0]
			Qu = Qu[1:]
			links[links[tmp]] ^= tmp
			counts[links[tmp]]--
			if counts[links[tmp]] == 1 {
				dists[links[tmp]] = int(math.Max(float64(stp), float64(dists[links[tmp]])))
				Qu = append(Qu, links[tmp])
			}
		}
		stp++
	}
	maxDist := 0
	for _, dist := range dists {
		if dist > maxDist {
			maxDist = dist
		}
	}
	res := make([]int, 0)
	for i, dist := range dists {
		if dist == maxDist {
			res = append(res, i)
		}
	}
	return res
}

1.13 - 2024-04-22 07:35:20 +0000 UTC

Find if Path Exists in Graph

Code

type UnionFind struct {
    parent []int
    rank   []int
}

func NewUnionFind(n int) *UnionFind {
    parent := make([]int, n)
    rank := make([]int, n)
    for i := 0; i < n; i++ {
        parent[i] = i
    }
    return &UnionFind{parent, rank}
}

func (uf *UnionFind) Find(u int) int {
    if uf.parent[u] != u {
        uf.parent[u] = uf.Find(uf.parent[u])
    }
    return uf.parent[u]
}

func (uf *UnionFind) UnionByRank(u, v int) {
    i := uf.Find(u)
    j := uf.Find(v)
    if i == j {
        return
    }
    if uf.rank[i] < uf.rank[j] {
        uf.parent[i] = j
    } else if uf.rank[i] > uf.rank[j] {
        uf.parent[j] = i
    } else {
        uf.parent[i] = j
        uf.rank[j]++
    }
}

func validPath(n int, edges [][]int, source int, destination int) bool {
    uf := NewUnionFind(n)
    for _, edge := range edges {
        u, v := edge[0], edge[1]
        uf.UnionByRank(u, v)
    }
    return uf.Find(source) == uf.Find(destination)
}

1.14 - 2024-04-22 07:16:09 +0000 UTC

Open the Lock

Code

import "strconv"

func openLock(deadends []string, target string) int {
    pow10 := []int{1, 10, 100, 1000}
    visit := make([]int, 10000) // 0: not visited, 1: visited through forward direction, -1: visited through backward direction, 2: deadends
    for _, dead := range deadends {
        num, _ := strconv.Atoi(dead)
        visit[num] = 2
    }
    src := 0
    dest, _ := strconv.Atoi(target)
    steps := 0
    dir := 1
    if visit[src] == 2 || visit[dest] == 2 {
        return -1
    }
    if src == dest {
        return 0
    }
    forward := make([]int, 0)
    backward := make([]int, 0)
    forward = append(forward, src)
    visit[src] = 1
    backward = append(backward, dest)
    visit[dest] = -1
    for len(forward) > 0 && len(backward) > 0 {
        if len(forward) > len(backward) {
            forward, backward = backward, forward
            dir = -dir
        }
        steps++
        size := len(forward)
        for j := 0; j < size; j++ {
            cur := forward[0]
            forward = forward[1:]
            for _, p := range pow10 {
                d := (cur / p) % 10
                for _, i := range []int{-1, 1} {
                    z := d + i
                    if z == -1 {
                        z = 9
                    } else if z == 10 {
                        z = 0
                    }
                    next := cur + (z-d)*p
                    if visit[next] == -dir {
                        return steps
                    }
                    if visit[next] == 0 {
                        forward = append(forward, next)
                        visit[next] = dir
                    }
                }
            }
        }
    }
    return -1
}

1.15 - 2024-04-20 18:02:52 +0000 UTC

Find All Groups of Farmland

Code

func findFarmland(land [][]int) [][]int {
	result := [][]int{}
	m, n := len(land), len(land[0])
	findFarmlandCoordinates := func(row, col int) []int {
		coordinates := []int{row, col}
		r, c := row, col
		for r < m && land[r][col] == 1 {
			r++
		}
		for c < n && land[row][c] == 1 {
			c++
		}
		coordinates = append(coordinates, r-1, c-1)
		for i := row; i < r; i++ {
			for j := col; j < c; j++ {
				land[i][j] = 0
			}
		}
		return coordinates
    }
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if land[i][j] == 1 {
				result = append(result, findFarmlandCoordinates(i, j))
			}
		}
	}
	return result
}

1.16 - 2024-04-19 07:37:47 +0000 UTC

Island Perimeter

Code

func islandPerimeter(grid [][]int) int {
    islands := 0
    neighbors := 0

    for i := 0; i < len(grid); i++ {
        for j := 0; j < len(grid[0]); j++ {
            if grid[i][j] == 1 {
                islands++
                if i-1 >= 0 && grid[i-1][j] == 1 {
                    neighbors++
                }
                if j-1 >= 0 && grid[i][j-1] == 1 {
                    neighbors++
                }
            }
        }
    }

    return islands*4 - neighbors*2
}

1.17 - 2024-04-19 07:37:20 +0000 UTC

Number of Islands

Code

func numIslands(grid [][]byte) int {
    if len(grid) == 0 || len(grid[0]) == 0 {
        return 0
    }
    
    rows := len(grid)
    cols := len(grid[0])
    islands := 0
    
    var dfs func(row, col int)
    dfs = func(row, col int) {
        if row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] != '1' {
            return
        }
        grid[row][col] = '0'
        dfs(row-1, col)
        dfs(row+1, col)
        dfs(row, col-1)
        dfs(row, col+1)
    }
    
    for row := 0; row < rows; row++ {
        for col := 0; col < cols; col++ {
            if grid[row][col] == '1' {
                dfs(row, col)
                islands++
            }
        }
    }
    
    return islands
}

1.18 - 2024-04-17 07:49:35 +0000 UTC

Smallest String Starting From Leaf

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func smallestFromLeaf(root *TreeNode) string {
	ans := ""
	var dfs func(node *TreeNode, text string)
	dfs = func(node *TreeNode, text string) {
		if node == nil {
			return
		}
		text = string(rune(node.Val + 97)) + text
		if node.Right == nil && node.Left == nil {
			if ans == "" || ans > text {
				ans = text
			}
			return
		}
		dfs(node.Left, text)
		dfs(node.Right, text)
	}

	dfs(root, "")
	return ans
}

1.19 - 2024-04-16 19:16:34 +0000 UTC

Add One Row to Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func addOneRow(root *TreeNode, val int, depth int) *TreeNode {
    if root == nil {
        return nil
    }

    if depth == 1 {
        root = &TreeNode{Val: val, Left: root}
    } else if (depth == 2) {
        root.Left = &TreeNode{Val: val, Left: root.Left}
        root.Right = &TreeNode{Val: val, Right: root.Right}
    } else {
        addOneRow(root.Left, val, depth - 1)
        addOneRow(root.Right, val, depth - 1)
    }

    return root;
}

1.20 - 2024-04-15 06:51:02 +0000 UTC

Sum Root to Leaf Numbers

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumNumbers(root *TreeNode) int {
    return dfs(root, 0)
}

func dfs(node *TreeNode, num int) int {
    if node == nil {
        return 0
    }
    if node.Left == nil && node.Right == nil {
        return num * 10 + node.Val
    }
    return dfs(node.Left, num * 10 + node.Val) + dfs(node.Right, num * 10 + node.Val)
}

1.21 - 2024-04-15 06:49:56 +0000 UTC

Sum of Left Leaves

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumOfLeftLeaves(root *TreeNode) int {
    if root == nil {
        return 0
    }

    left := 0
    if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
        left = root.Left.Val
    }

    return left + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}

1.22 - 2024-04-13 15:32:47 +0000 UTC

Maximal Rectangle

Code

func maximalRectangle(matrix [][]byte) int {
    heights := make([]int, len(matrix[0]) + 1)
    heights[len(heights)-1] = -1
    mx := 0
    for _, row := range matrix {
        for i := range row {
            if row[i] == '1' {
                heights[i]++
            } else {
                heights[i] = 0
            }
        }

        stack := []int{}
        for i, currentHeight := range heights {
            for len(stack) > 0 && heights[stack[len(stack)-1]] > currentHeight {
                prev := heights[stack[len(stack)-1]]
                stack = stack[:len(stack)-1]

                width := i
                if len(stack) > 0 {
                    width = i - stack[len(stack)-1] - 1
                }
                mx = max(mx, prev * width)
            }
            stack = append(stack, i)
        } 
    }
    return mx
}

1.23 - 2024-04-12 07:40:19 +0000 UTC

Trapping Rain Water

Code

func trap(height []int) int {
	var waterStored int
	leftElevationPoint, rightElevationPoint := 0, len(height)-1                                    // pointers for left and right elevations
	maxLeftElevation, maxRightElevation := height[leftElevationPoint], height[rightElevationPoint] // max value of left and right elevation points

	for leftElevationPoint < rightElevationPoint { // until left elevation point reaches right elevation point or right elevation point reaches left elevation point
		if maxLeftElevation < maxRightElevation { // if max left elevation is smaller than max right elevation
			leftElevationPoint++                               // move the left elevation point by 1
			if height[leftElevationPoint] > maxLeftElevation { // if height of current left elevation after moving is greater than max left elevation
				maxLeftElevation = height[leftElevationPoint] // swap the max left elevation with current left elevation point value
			}
			waterStored += maxLeftElevation - height[leftElevationPoint] // store water with delta of max left elevation and current left elevation
		} else {
			rightElevationPoint--                                // decrease the right elevation by 1
			if height[rightElevationPoint] > maxRightElevation { // if height of current right elevation after decreasing is greater than max right elevation
				maxRightElevation = height[rightElevationPoint] // swap the max right elevation with current right elevation point value
			}
			waterStored += maxRightElevation - height[rightElevationPoint] // store water with delta of max right elevation and current right elevation
		}
	}

	return waterStored
}

1.24 - 2024-04-11 10:44:41 +0000 UTC

Remove K Digits

Code

func removeKdigits(num string, k int) string {
	res := make([]rune, 0)
    
	for _, c := range num {
		for len(res) > 0 && res[len(res) - 1] > c && k > 0 {
			res = res[:len(res) - 1]
			k--
		}

		if len(res) > 0 || c != '0' {
			res = append(res, c)
		}
	}

	for len(res) > 0 && k > 0 {
		res = res[:len(res) - 1]
		k--
	}

	if len(res) == 0 {
		return "0"
	}
	return string(res)
}

1.25 - 2024-04-10 10:25:18 +0000 UTC

Reveal Cards In Increasing Order

Code

func deckRevealedIncreasing(deck []int) []int {
	n := len(deck)
	sort.Ints(deck)

	res := make([]int, n)
	queue := make([]int, n)

	for i := range queue {
		queue[i] = i
	}

	for _, card := range deck {
		idx := queue[0]
		queue = queue[1:]
		res[idx] = card

		if len(queue) > 0 {
			queue = append(queue, queue[0])
			queue = queue[1:]
		}
	}

	return res
}

1.26 - 2024-04-09 11:21:46 +0000 UTC

Time Needed to Buy Tickets

Code

func timeRequiredToBuy(tickets []int, k int) int {
    n := len(tickets)
    d := tickets[k]
    res := 0
    for i := 0; i <= k; i++ {
        res += min(d, tickets[i])
    }
    for i := k + 1; i < n; i++ {
        res += min(d - 1, tickets[i])
    }
    return res
}

1.27 - 2024-04-08 08:25:34 +0000 UTC

Number of Students Unable to Eat Lunch

Code

func countStudents(students []int, sandwiches []int) int {
    req := make([]int, 2)
    for _, student := range students {
        req[student]++
    }

    for _, sandwich := range sandwiches {
        if req[sandwich] == 0 {
            return req[1 - sandwich]
        } else {
            req[sandwich]--
        }
    }

    return 0
}

1.28 - 2024-04-07 08:42:18 +0000 UTC

Valid Parenthesis String

Code

func checkValidString(s string) bool {
    open := 0
    openMax := 0
    for _, char := range s {
        switch char {
        case '(':
            open++
            openMax++
        case ')':
            open--
            openMax--
        default:
            open--
            openMax++
        }
        if openMax < 0 {
            return false
        }
        if open < 0 {
            open = 0
        }
    }
    return open == 0
}

1.29 - 2024-04-07 08:41:54 +0000 UTC

Minimum Remove to Make Valid Parentheses

Code

type stack struct {
    top   int
    v     []byte
    index []int
}

func minRemoveToMakeValid(s string) string {
    stc := stack{top: -1}

    // collect bad brackets
    for i, v := range s {
        if v == '(' {
            stc.v = append(stc.v, '(')
            stc.index = append(stc.index, i)
            stc.top++
        } else if v == ')' {
            if stc.top > -1 && stc.v[stc.top] == '(' {
                stc.v = stc.v[:stc.top]
                stc.index = stc.index[:stc.top]
                stc.top--
            } else {
                stc.v = append(stc.v, ')')
                stc.index = append(stc.index, i)
                stc.top++
            }
        }
    }

    // remove them
    res := []byte{}
    i := 0
    for _, v := range stc.index {
        res = append(res, s[i:v]...)
        i = v + 1
    }

    // checking of end
    if len(res) + len(stc.index) < len(s) {
        res = append(res, s[i:]...)
    }

    return string(res)
}

1.30 - 2024-04-05 14:17:39 +0000 UTC

Make The String Great

Code

func makeGood(s string) string {
	stack := make([]byte, 0, len(s))
	stack = append(stack, s[0])
	for i := 1; i < len(s); i++ {
		if len(stack) > 0 && getDiff(stack[len(stack)-1], s[i]) == 32 {
			stack = stack[:len(stack)-1]
			continue
		}
		stack = append(stack, s[i])
	}
	return string(stack)
}

func getDiff(a, b uint8) uint8 {
	if b > a {
		return b - a
	}
	return a - b
}

1.31 - 2024-04-04 13:06:45 +0000 UTC

Maximum Nesting Depth of the Parentheses

Code

func maxDepth(s string) int {
    maxDepth := 0
    curDepth := 0
    for _, ch := range s {
        if ch == '(' {
            curDepth++
            maxDepth = max(maxDepth, curDepth)
        } else if ch == ')' {
            curDepth--
        }
    }
    return maxDepth
}

1.32 - 2024-04-03 07:52:54 +0000 UTC

Word Search

Code

func exist(board [][]byte, word string) bool {
    if nLetters := len(board) * len(board[0]); nLetters < len(word) {
        return false
    }

    for i := range board {
        for j := range board[i] {
            if dfs(i, j, 0, board, word, make(map[pair]struct{})) {
                return true
            }
        }
    }

    return false
}

type pair struct {
    r, c int
}

func dfs(r, c, i int, board [][]byte, word string, visited map[pair]struct{}) bool {
    if i == len(word) {
        return true
    }

    inBounds := r >= 0 && r < len(board) && c >= 0 && c < len(board[0])
    if _, ok := visited[pair{r, c}]; !inBounds || ok || word[i] != board[r][c] {
        return false
    }

    visited[pair{r, c}] = struct{}{}

    up := dfs(r+1, c, i+1, board, word, visited)
    down := dfs(r-1, c, i+1, board, word, visited)
    right := dfs(r, c+1, i+1, board, word, visited)
    left := dfs(r, c-1, i+1, board, word, visited)

    delete(visited, pair{r, c})

    return up || down || right || left
}

1.33 - 2024-04-02 14:28:57 +0000 UTC

Isomorphic Strings

Code

func isIsomorphic(s string, t string) bool {
    map1 := make([]int, 128) // Stores frequency of s
    map2 := make([]int, 128) // Stores frequency of t

    for i := 0; i < len(s); i++ {
        sCh := s[i]
        tCh := t[i]

        if map1[sCh] == 0 && map2[tCh] == 0 {
            map1[sCh] = int(tCh)
            map2[tCh] = int(sCh)
        } else if map1[sCh] != int(tCh) || map2[tCh] != int(sCh) {
            return false
        }
    }
    return true
}

1.34 - 2024-04-01 15:03:03 +0000 UTC

Length of Last Word

Code

func lengthOfLastWord(s string) int {
    length := len(s)
    count := 0
    for i := length - 1; i >= 0; i-- {
        isSpace := s[i] == ' '
        if isSpace && count != 0 {
            return count
        } else if isSpace {
            continue
        }
        count++
    }
    return count
}

1.35 - 2024-03-31 07:58:30 +0000 UTC

Count Subarrays With Fixed Bounds

Code

func countSubarrays(nums []int, minK int, maxK int) int64 {
    var res int64
	left := 0
	pmin := -1
	pmax := -1

	for right, num := range nums {
		if num < minK || num > maxK {
			left = right + 1
			pmin = -1
			pmax = -1
		} else {
			if num == minK {
				pmin = right
			}
			if num == maxK {
				pmax = right
			}
			res += int64(max(0, min(pmin, pmax) - left + 1))
		}
	}

	return res
}

1.36 - 2024-03-30 16:24:47 +0000 UTC

Subarrays with K Different Integers

Code

func subarraysWithAtMostKDistinct(nums []int, k int) int {
    if k == 0 {
        return 0
    }

    countOccurrence := make(map[int]int)
    differentIntegers := 0
    left := 0
    result := 0

    for right := 0; right < len(nums); right++ {
        countOccurrence[nums[right]]++
        if countOccurrence[nums[right]] == 1 {
            differentIntegers++
        }

        for differentIntegers > k {
            countOccurrence[nums[left]]--
            if countOccurrence[nums[left]] == 0 {
                differentIntegers--
            }
            left++
        }

        result += right - left + 1
    }
    return result
}

func subarraysWithKDistinct(nums []int, k int) int {
    return subarraysWithAtMostKDistinct(nums, k) - subarraysWithAtMostKDistinct(nums, k-1)
}

1.37 - 2024-03-29 11:30:16 +0000 UTC

Count Subarrays Where Max Element Appears at Least K Times

Code

func countSubarrays(nums []int, k int) int64 {
	maxValue := 0
	var maxValueIds []int
	var ans int64

	for i, x := range nums {
		if x > maxValue {
			maxValue, ans, maxValueIds = x, 0, []int{}
		}

		if x == maxValue {
			maxValueIds = append(maxValueIds, i)
		}

		if len(maxValueIds) >= k {
			ans += int64(maxValueIds[len(maxValueIds)-k]) + 1
		}
	}

	return ans
}

1.38 - 2024-03-28 16:02:58 +0000 UTC

Length of Longest Subarray With at Most K Frequency

Code

func maxSubarrayLength(nums []int, k int) int {
    i := 0
    j := 0
    n := len(nums)
    ans := 1
    mp := make(map[int]int)

    for i < n {
        mp[nums[i]]++
        for mp[nums[i]] > k {
            mp[nums[j]]--
            j++
        }
        if i-j+1 > ans {
            ans = i - j + 1
        }
        i++
    }
    return ans
}

1.39 - 2024-03-27 15:55:43 +0000 UTC

Subarray Product Less Than K

Code

func numSubarrayProductLessThanK(nums []int, k int) int {
	if k <= 1 {
		return 0
	}

	l := 0
	p := 1
	res := 0
	for r, num := range nums {
		p *= num
		for p >= k {
			p /= nums[l]
			l++
		}
        
		res += r - l + 1
	}

	return res
}

1.40 - 2024-03-26 07:04:37 +0000 UTC

First Missing Positive

Code

func firstMissingPositive(nums []int) int {
    n := len(nums)

	for i := 0; i < n; i++ {
		if nums[i] <= 0 || nums[i] > n {
			nums[i] = n + 1
		}
	}

	for i := 0; i < n; i++ {
		val := abs(nums[i])
		if val >= 1 && val <= n {
			flagIndex := val - 1
			if nums[flagIndex] > 0 {
				nums[flagIndex] *= -1
			}
		}
	}

	for i := 1; i <= n; i++ {
		if nums[i - 1] > 0 {
			return i
		}
	}

	return n + 1
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

1.41 - 2024-03-25 16:23:11 +0000 UTC

Find All Duplicates in an Array

Code

func findDuplicates(nums []int) []int {
    output := []int{}
    for _, num := range nums {
        idx := abs(num)
        if nums[idx-1] < 0 {
            output = append(output, idx)
        } else {
            nums[idx-1] *= -1
        }
    }
    return output
}
func abs(num int) int {
    if num < 0 {
        return -num
    }
    return num
}

1.42 - 2024-03-24 11:27:34 +0000 UTC

Find the Duplicate Number

Code

func findDuplicate(nums []int) int {
    seen := make(map[int]struct{})
    for _, num := range nums {
        if _, ok := seen[num]; ok {
            return num
        }
        seen[num] = struct{}{}
    }
    return -1
}

1.43 - 2024-03-24 11:27:17 +0000 UTC

Find the Duplicate Number

Code

func findDuplicate(nums []int) int {
    seen := make(map[int]struct{}, len(nums) - 1)
    for _, num := range nums {
        if _, ok := seen[num]; ok {
            return num
        }
        seen[num] = struct{}{}
    }
    return -1
}

1.44 - 2024-03-23 17:51:44 +0000 UTC

Reorder List

Code

func reorderList(head *ListNode) {
    if head == nil || head.Next == nil {
        return
    }

    middle := midNode(head)
    newHead := middle.Next
    middle.Next = nil

    newHead = reverseLinkedList(newHead)

    c1 := head
    c2 := newHead
    var f1, f2 *ListNode

    for c1 != nil && c2 != nil {
        // Backup
        f1 = c1.Next
        f2 = c2.Next

        // Linking
        c1.Next = c2
        c2.Next = f1

        // Move
        c1 = f1
        c2 = f2
    }
}

func midNode(head *ListNode) *ListNode {
    slow := head
    fast := head

    for fast.Next != nil && fast.Next.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
    }
    return slow
}

func reverseLinkedList(head *ListNode) *ListNode {
    var prev, curr, forw *ListNode = nil, head, nil

    for curr != nil {
        forw = curr.Next
        curr.Next = prev
        prev = curr
        curr = forw
    }
    return prev
}

1.45 - 2024-03-22 08:45:00 +0000 UTC

Palindrome Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func isPalindrome(head *ListNode) bool {
    nodes := []int{}
    for head != nil {
        nodes = append(nodes, head.Val)
        head = head.Next
    }
    length := len(nodes)
    for i := range(length / 2) {
        start, end := nodes[i], nodes[length-i-1]
        if start != end {
            return false
        }
    }
    return true
}

1.46 - 2024-03-22 08:41:12 +0000 UTC

Reverse Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    if head == nil {
        return nil
    }
    cur, next := head, head.Next
    head.Next = nil
    for next != nil {
        cur, next, next.Next = next, next.Next, cur
    }
    return cur
}

1.47 - 2024-03-21 11:09:24 +0000 UTC

Reverse Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    if head == nil {
        return nil
    }
    cur, next := head, head.Next
    head.Next = nil
    for next != nil {
        cur, next, next.Next = next, next.Next, cur
    }
    return cur
}

1.48 - 2024-03-21 11:05:27 +0000 UTC

Reverse Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    if head == nil {
        return nil
    }
    cur, next := head, head.Next
    cur.Next = nil
    for next != nil {
        cur, next, next.Next = next, next.Next, cur
    }
    return cur
}

1.49 - 2024-03-21 10:53:28 +0000 UTC

Merge In Between Linked Lists

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
    if list1 == nil {
        return list2 
    }
    list2Head, list2Tail := list2, list2
    for list2 != nil {
        list2Tail = list2
        list2 = list2.Next
    }
    count := 0
    list1Head := list1
    for list1 != nil {
        next := list1.Next
        if count == a - 1 {
            list1.Next = list2Head
        } else if count == b {
            list2Tail.Next = list1.Next
        }
        list1 = next
        count++
    }
    return list1Head
}

1.50 - 2024-03-20 18:13:36 +0000 UTC

Task Scheduler

Code

func leastInterval(tasks []byte, n int) int {
	if n == 0 {
		return len(tasks)
	}

	cnt := make([]int, 26)
	for _, task := range tasks {
		cnt[task - 'A']++
	}

	var maxCount, sameMaxCount int
	for _, c := range cnt {
		if c > maxCount {
			maxCount = c
			sameMaxCount = 1
		} else if c == maxCount {
			sameMaxCount++
		}
	}

	res := (n + 1) * (maxCount - 1) + sameMaxCount
    if (res > len(tasks)) {
        return res
    } else {
        return len(tasks)
    }
}

1.51 - 2024-03-20 18:12:54 +0000 UTC

Merge In Between Linked Lists

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
    l := list1
    for i := 1; i <= a - 1; i++ {
        l = l.Next
    }

    prev := l
    r := l
    for i := a; i <= b + 1; i++ {
        r = r.Next
        prev.Next = nil
        prev = r
    }

    list2Tail := list2
    for list2Tail.Next != nil {
        list2Tail = list2Tail.Next
    }

    l.Next = list2
    list2Tail.Next = r

    return list1
}

1.52 - 2024-03-18 16:30:56 +0000 UTC

Minimum Number of Arrows to Burst Balloons

Code

func findMinArrowShots(points [][]int) int {
    // Sort the balloons based on their end coordinates
    sort.Slice(points, func(i, j int) bool {
        return points[i][1] < points[j][1]
    })

    arrows := 1
    prevEnd := points[0][1]

    // Count the number of non-overlapping intervals
    for i := 1; i < len(points); i++ {
        if points[i][0] > prevEnd {
            arrows++
            prevEnd = points[i][1]
        }
    }

    return arrows
}

1.53 - 2024-03-17 09:32:47 +0000 UTC

Contiguous Array

Code

func findMaxLength(nums []int) int {
    hashmap := make(map[int]int)
    zeros, ones, maxLen := 0, 0, 0
    hashmap[0] = -1 
    for i, num := range nums {
        if num == 0 {
            zeros++
        } else {
            ones++
        }
        diff := zeros - ones
        if val, ok := hashmap[diff]; ok {
            maxLen = max(maxLen, i - val)
        } else {
            hashmap[diff] = i
        }
    }
    return maxLen
}

1.54 - 2024-03-17 09:32:06 +0000 UTC

Insert Interval

Code

func insert(intervals [][]int, newInterval []int) [][]int {
	var result [][]int

    // Iterate through intervals and add non-overlapping intervals before newInterval
	i := 0
	for i < len(intervals) && intervals[i][1] < newInterval[0] {
		result = append(result, intervals[i])
		i++
	}

    // Merge overlapping intervals
	for i < len(intervals) && intervals[i][0] <= newInterval[1] {
		newInterval[0] = int(math.Min(float64(newInterval[0]), float64(intervals[i][0])))
		newInterval[1] = int(math.Max(float64(newInterval[1]), float64(intervals[i][1])))
		i++
	}

    // Add merged newInterval
	result = append(result, newInterval)

    // Add non-overlapping intervals after newInterval
	for i < len(intervals) {
		result = append(result, intervals[i])
		i++
	}

	return result
}

1.55 - 2024-03-15 17:15:18 +0000 UTC

Product of Array Except Self

Code

func productExceptSelf(nums []int) []int {
    n := len(nums)
    res := make([]int, n)

    preProduct := 1
    for i := 0; i < n; i++ {
        res[i] = preProduct
        preProduct *= nums[i]
    }

    sufProduct := 1
    for i := n - 1; i >= 0; i-- {
        res[i] *= sufProduct
        sufProduct *= nums[i]
    }

    return res
}

1.56 - 2024-03-14 16:06:22 +0000 UTC

Binary Subarrays With Sum

Code

func numSubarraysWithSum(nums []int, goal int) int {

    hashmap := make(map[int]int)

    hashmap[0] = 1

    sum := 0

    count := 0



    for _, num := range nums {

        sum += num

        rem := sum - goal

        if val, ok := hashmap[rem]; ok {

            count += val

        }

        hashmap[sum]++

    }



    return count

}

1.57 - 2024-03-13 16:53:19 +0000 UTC

Find the Pivot Integer

Code

func getSum(x int) int {
	return x * (x + 1) / 2
}

func pivotInteger(n int) int {
    sum := getSum(n)

	l, r := 1, n
	for l <= r {
		m := (l + r) / 2
		firstPart := getSum(m)
		secondPart := sum - firstPart + m

		if firstPart == secondPart {
			return m
		} else if firstPart > secondPart {
			r = m - 1
		} else {
			l = m + 1
		}
	}

	return -1
}

1.58 - 2024-03-12 16:08:41 +0000 UTC

Remove Zero Sum Consecutive Nodes from Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeZeroSumSublists(head *ListNode) *ListNode {
    dummy := &ListNode{0, head}
    prefixSumToNode := make(map[int]*ListNode)
    prefixSum := 0
    for current := dummy; current != nil; current = current.Next {
        prefixSum += current.Val
        if prev, found := prefixSumToNode[prefixSum]; found {
            toRemove := prev.Next
            p := prefixSum
            if toRemove != nil {
                p += toRemove.Val
            }
            for toRemove != nil && p != prefixSum {
                delete(prefixSumToNode, p)
                toRemove = toRemove.Next
                if toRemove != nil {
                    p += toRemove.Val
                }
            }
            prev.Next = current.Next
        } else {
            prefixSumToNode[prefixSum] = current
        }
    }
    return dummy.Next
}

1.59 - 2024-03-11 16:30:24 +0000 UTC

Custom Sort String

Code

func customSortString(order string, s string) string {
    count := make([]int, 26)

    for _, c := range s {
        count[c-'a']++
    }

    var result strings.Builder

    for _, c := range order {
        result.WriteString(strings.Repeat(string(c), count[c-'a']))
        count[c-'a'] = 0
    }

    for i := 0; i < 26; i++ {
        result.WriteString(strings.Repeat(string('a'+i), count[i]))
    }
    // UPVOTE :)
    return result.String()
}

1.60 - 2024-03-10 19:58:44 +0000 UTC

Intersection of Two Arrays

Code

func intersection(nums1 []int, nums2 []int) []int {
    seen := make([]int, 1000)
    for i := range nums1 {
        seen[nums1[i]]++
    }

    res := make([]int, 0)
    for i := range nums2 {
        if seen[nums2[i]] > 0 {
            res = append(res, nums2[i])
            seen[nums2[i]] = 0
        }
    }

    return res
}

1.61 - 2024-03-09 16:01:11 +0000 UTC

Count Elements With Maximum Frequency

Code

func maxFrequencyElements(nums []int) int {
    mapCount := make(map[int]int)

    for _, val := range nums {
        mapCount[val]++
    }

    count := 0
    max := -1
    for _, freq := range mapCount {
        if freq > max {
            max = freq
        }
    }

    for _, freq := range mapCount {
        if freq == max {
            count += max
        }
    }
    return count
}

1.62 - 2024-03-09 15:59:53 +0000 UTC

Minimum Common Value

Code

func getCommon(nums1 []int, nums2 []int) int {
    var l, r int
    for l < len(nums1) && r < len(nums2) {
        switch {
        case nums1[l] == nums2[r]:
            return nums1[l]
        case nums1[l] < nums2[r]:
            l++
        default:
            r++
        }
    }
    return -1
}

1.63 - 2024-03-07 16:08:46 +0000 UTC

Middle of the Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func middleNode(head *ListNode) *ListNode {
    if head.Next == nil {
        return head
    }
    slow, fast := head, head.Next
    move := true
    for fast.Next != nil {
        if move {
            slow = slow.Next
            move = false
        } else {
            move = true
        }
        fast = fast.Next
    }
    if move {
        return slow.Next
    }
    return slow
}

1.64 - 2024-03-07 16:07:46 +0000 UTC

Middle of the Linked List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func middleNode(head *ListNode) *ListNode {
    if head.Next == nil {
        return head
    }
    slow, fast := head, head.Next
    move := true
    for fast.Next != nil {
        if move {
            slow = slow.Next
            move = false
        } else {
            move = true
        }
        fast = fast.Next
    }
    if move {
        slow = slow.Next
    }
    return slow
}

1.65 - 2024-03-06 13:05:23 +0000 UTC

Linked List Cycle

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {
    nodes := map[*ListNode]struct{}{}
    for head != nil {
        if _, ok := nodes[head]; ok {
            return true
        }
        nodes[head] = struct{}{}
        head = head.Next
    }
    return false
}

1.66 - 2024-03-05 08:52:38 +0000 UTC

Minimum Length of String After Deleting Similar Ends

Code

func minimumLength(s string) int {
    left := 0
    right := len(s) - 1
    
    for left < right {
        lc := s[left]
        rc := s[right]
        
        if lc != rc {
            return right - left + 1
        }
        
        for left + 1 < right && lc == s[left + 1] {
            left++
        }
        
        for left < right - 1 && rc == s[right - 1] {
            right--
        }
        
        right--
        left++
    }
    
    return right - left + 1
}

1.67 - 2024-03-04 13:21:41 +0000 UTC

Bag of Tokens

Code

func bagOfTokensScore(tokens []int, power int) int {
    n := len(tokens)
	sort.Ints(tokens)
	res := 0

	l := 0
	r := n - 1

	for l <= r {
		for l <= r && power >= tokens[l] {
			power -= tokens[l]
			l++
			res++
		}
		
		if res == 0 {
			break
		}

        if r - l + 1 <= 2 {
			break
		}

		power += tokens[r]
		r--
		res--
	}

	return res
}

1.68 - 2024-03-03 07:57:46 +0000 UTC

Remove Nth Node From End of List

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
    res := &ListNode{0, head}

    lead := res
    for i := 0; i <= n; i++ {
        lead = lead.Next
    }

    cur := res
    for lead != nil {
        cur = cur.Next
        lead = lead.Next
    }

    cur.Next = cur.Next.Next
    return res.Next
}

1.69 - 2024-03-02 12:59:13 +0000 UTC

Squares of a Sorted Array

Code

func sortedSquares(nums []int) []int {
    for i, num := range nums {
        if num < 0 {
            nums[i] = -num
        } else { 
            break
        }
    }
    slices.Sort(nums)
    for i, num := range nums {
        nums[i] = num * num
    }
    return nums
}

1.70 - 2024-03-02 12:57:16 +0000 UTC

Squares of a Sorted Array

Code

func sortedSquares(nums []int) []int {
    for i, num := range nums {
        nums[i] = num * num
    }
    slices.Sort(nums)
    return nums
}

1.71 - 2024-03-02 12:56:40 +0000 UTC

Squares of a Sorted Array

Code

func sortedSquares(nums []int) []int {
    for i, num := range nums {
        if num < 0 {
            nums[i] = -num
        }
    }
    slices.Sort(nums)
    for i, num := range nums {
        nums[i] = num * num
    }
    return nums
}

1.72 - 2024-03-01 15:28:31 +0000 UTC

Maximum Odd Binary Number

Code

func maximumOddBinaryNumber(s string) string {
	l := len(s)
	res := make([]byte, l)
	index0, index1 := l-2, l-1
	for i := 0; i < l; i++ {
		if s[i] == '0' {
			res[index0] = '0'
			index0--
		} else {
			res[index1] = '1'
			index1 = (index1 + 1) % l
		}
	}
	return string(res)
}

1.73 - 2024-02-29 14:38:44 +0000 UTC

Even Odd Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isEvenOddTree(root *TreeNode) bool {
    q := []*TreeNode{root}
    for i:= 0; len(q) > 0; i++ {
        var prev *TreeNode
        for _, node := range q {
            q = q[1:]

            if i % 2 == 0 && node.Val % 2 != 1 {
                return false
            }

            if i % 2 == 1 && node.Val % 2 != 0 {
                return false
            }

            if prev != nil && i % 2 == 0 && prev.Val >= node.Val {
                return false
            }

            if prev != nil && i % 2 == 1 && prev.Val <= node.Val {
                return false
            }
           
            prev = node
            if node.Left != nil {
                q = append(q, node.Left)
            }

            if node.Right != nil {
                q = append(q, node.Right)
            }
        }
    }
    return true
}

1.74 - 2024-02-28 09:31:13 +0000 UTC

Find Bottom Left Tree Value

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findBottomLeftValue(root *TreeNode) int {
    _, val := getBottomLeft(root)
    return val
}

func getBottomLeft(root *TreeNode) (int, int) {
    left, right := root.Left, root.Right
    if right == nil && left == nil {
        return 0, root.Val
    }
    if right == nil {
        depth, val := getBottomLeft(root.Left)
        return 1 + depth, val
    }
    if left == nil {
        depth, val := getBottomLeft(root.Right)
        return 1 + depth, val
    }
    leftDepth, leftVal := getBottomLeft(root.Left)
    rightDepth, rightVal := getBottomLeft(root.Right)
    if rightDepth > leftDepth {
        return 1 + rightDepth, rightVal
    }
    return 1 + leftDepth, leftVal
}

1.75 - 2024-02-27 16:25:53 +0000 UTC

Diameter of Binary Tree

Code

var maxD int

func diameterOfBinaryTree(root *TreeNode) int {
    maxD = 0
    find(root)
    return maxD
}

func find(root *TreeNode) int {
    if root == nil {
        return 0
    }
    left := find(root.Left)
    right := find(root.Right)
    localMax := left + right
    maxD = max(maxD, localMax)
    return max(left, right) + 1
}

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

1.76 - 2024-02-26 16:57:46 +0000 UTC

Same Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    if p == nil || q == nil || p.Val != q.Val {
        return false
    }
    return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}

1.77 - 2024-02-25 17:04:05 +0000 UTC

Greatest Common Divisor Traversal

Code

func canTraverseAllPairs(nums []int) bool {
    if len(nums) == 1 {
        return true
    }
    n := len(nums)
    maxElement := nums[0]
    minElement := nums[0]
    for _, num := range nums {
        if num > maxElement {
            maxElement = num
        }
        if num < minElement {
            minElement = num
        }
    }
    if minElement == 1 {
        return false
    }
    factorArray := factorsCalculator(maxElement)

    parent := make([]int, maxElement+1)
    rank := make([]int, maxElement+1)
    for i := 0; i <= maxElement; i++ {
        parent[i] = i
        rank[i] = 1
    }

    for _, num := range nums {
        x := num
        for x > 1 {
            p := factorArray[x]
            union(parent, rank, p, num)
            for x%p == 0 {
                x = x / p
            }
        }
    }

    p := find(parent, nums[0])
    for i := 1; i < n; i++ {
        if find(parent, nums[i]) != p {
            return false
        }
    }

    return true
}

func factorsCalculator(n int) []int {
    dp := make([]int, n+2)
    for i := 0; i < len(dp); i++ {
        dp[i] = i
    }
    for i := 2; i <= n; i++ {
        if dp[i] == i {
            for j := i * 2; j <= n; j += i {
                if dp[j] == j {
                    dp[j] = i
                }
            }
        }
    }
    return dp
}

func find(parent []int, a int) int {
    if parent[a] == a {
        return a
    }
    parent[a] = find(parent, parent[a])
    return parent[a]
}

func union(parent []int, rank []int, a int, b int) {
    a = find(parent, a)
    b = find(parent, b)
    if a == b {
        return
    }
    if rank[a] < rank[b] {
        a, b = b, a
    }
    parent[b] = a
    rank[a] += rank[b]
}

1.78 - 2024-02-24 12:45:37 +0000 UTC

Find All People With Secret

Code

package main

import (
	"sort"
)

func find(groups []int, index int) int {
	for index != groups[index] {
		index = groups[index]
	}
	return index
}

func findAllPeople(n int, meetings [][]int, firstPerson int) []int {
	groups := make([]int, 100000)
	var result []int
	var temp []int

	for i := 0; i < n; i++ {
		groups[i] = i
	}
	groups[firstPerson] = 0

	sort.Slice(meetings, func(i, j int) bool {
		return meetings[i][2] < meetings[j][2]
	})

	i := 0
	for i < len(meetings) {
		currentTime := meetings[i][2]
		temp = temp[:0]
		for i < len(meetings) && meetings[i][2] == currentTime {
			g1 := find(groups, meetings[i][0])
			g2 := find(groups, meetings[i][1])
			groups[max(g1, g2)] = min(g1, g2)
			temp = append(temp, meetings[i][0], meetings[i][1])
			i++
		}
		for _, j := range temp {
			if find(groups, j) != 0 {
				groups[j] = j
			}
		}
	}

	for j := 0; j < n; j++ {
		if find(groups, j) == 0 {
			result = append(result, j)
		}
	}

	return result
}

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

1.79 - 2024-02-23 09:30:25 +0000 UTC

Cheapest Flights Within K Stops

Code

type Connection struct {
	city int
	cost int
}

type queue []Connection

func (q *queue) push(c Connection) {
	q1 := []Connection{c}
	*q = append(*q, q1...)
}

func (q *queue) pop() (bool, Connection) {

	if q.isEmpty() {
		return false, Connection{}
	} else {
		elem := (*q)[0]
		*q = (*q)[1:]
		return true, elem
	}
}

func (q queue) isEmpty() bool {
	return q.size() <= 0
}

func (q queue) size() int {
	return len(q)
}

func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {

	minCost := math.MaxInt64

	fQueue := new(queue)
	fQueue.push(Connection{src, 0})

	maxStops := k + 1

	costOfFlights := make([][]int, n)
	for i := range costOfFlights {
		costOfFlights[i] = make([]int, n)
	}

	flightsMap := make(map[int][]int)
	for _, v := range flights {
		if _, ok := flightsMap[v[0]]; ok {
			flightsMap[v[0]] = append(flightsMap[v[0]], v[1])
		} else {
			flightsMap[v[0]] = []int{v[1]}
		}

		costOfFlights[v[0]][v[1]] = v[2]
	}

	cityPathCost := make([]int, n) // path cost from source
	for i := range cityPathCost {
		cityPathCost[i] = math.MaxInt64
	}

	cityPathCost[src] = 0

	for !fQueue.isEmpty() && maxStops >= 0 {

		size := fQueue.size()
		maxStops--

		for size > 0 {
			_, c := fQueue.pop()
			size--

			if c.city == dst {
				if minCost > c.cost {
					minCost = c.cost
				}
				continue
			}

			for _, v := range flightsMap[c.city] {

				newCost := c.cost + costOfFlights[c.city][v]

				if cityPathCost[v] > newCost {
					fQueue.push(Connection{v, newCost})
					cityPathCost[v] = newCost
				}
			}
		}
	}

	if minCost == math.MaxInt64 {
		minCost = -1
	}

	return minCost
}

1.80 - 2024-02-22 08:20:36 +0000 UTC

Find the Town Judge

Code

func findJudge(n int, trust [][]int) int {
    fromTo := make([][]int, n)
    toFrom := make([][]int, n)
    for _, trustArray := range trust {
        from, to := trustArray[0], trustArray[1]
        fromTo[from-1] = append(fromTo[from-1], to)
        toFrom[to-1] = append(toFrom[to-1], from)
    }
    for i, from := range toFrom {
        if len(from) == n - 1 && len(fromTo[i]) == 0 {
            return i + 1
        }
    }
    return -1
}

1.81 - 2023-11-10 10:30:38 +0000 UTC

Restore the Array From Adjacent Pairs

Code

func restoreArray(adjacentPairs [][]int) []int {
    // [[2,1],[3,4],[3,2]]
    // 1: [2]
    // 2: [1, 3]
    // 3: [2, 4]
    // 4: [3]
    // Output: [1,2,3,4]
    graph := map[int][]int{}
    length := len(adjacentPairs) + 1
    ans := make([]int, length)
    for _, pair := range adjacentPairs {
        num1, num2 := pair[0], pair[1]
        graph[num1] = append(graph[num1], num2)
        graph[num2] = append(graph[num2], num1)
    }
    for node, edges := range graph {
        if len(edges) == 1 {
            ans[0], ans[1] = node, edges[0]
            break
        }
    }
    cur, prev := ans[1], ans[0]
    for i := 2; i < length; i++ {
        for _, target := range graph[cur] {
            if target != prev {
                ans[i] = target
                cur, prev = target, cur
                break
            }
        }
    }
    return ans
}

1.82 - 2023-11-10 10:24:56 +0000 UTC

Restore the Array From Adjacent Pairs

Code

func restoreArray(adjacentPairs [][]int) []int {
    // [[2,1],[3,4],[3,2]]
    // 1: [2]
    // 2: [1, 3]
    // 3: [2, 4]
    // 4: [3]
    // Output: [1,2,3,4]
    graph := map[int][]int{}
    for _, pair := range adjacentPairs {
        num1, num2 := pair[0], pair[1]
        graph[num1] = append(graph[num1], num2)
        graph[num2] = append(graph[num2], num1)
    }
    length := len(adjacentPairs) + 1
    ans := make([]int, length)
    for node, edges := range graph {
        if len(edges) == 1 {
            ans[0], ans[1] = node, edges[0]
            break
        }
    }
    for i := 2; i < length; i++ {
        cur, prev := ans[i-1], ans[i-2]
        for _, target := range graph[cur] {
            if target != prev {
                ans[i] = target
            }
        }
    }
    return ans
}

1.83 - 2023-11-09 07:03:41 +0000 UTC

Count Number of Homogenous Substrings

Code

func countHomogenous(s string) int {
    var (
        mod int64 = 1000000007 
        total int64 = 0
        count int64 = 0
        cur = s[0]
    )
    
    for i := 0; i < len(s); i++ {
        char := s[i]
        if char == cur {
            count++
        } else {
            count = 1
            cur = char
        }
        total += count
    }
    
    return int(total % mod)
}

1.84 - 2023-11-08 08:09:02 +0000 UTC

Determine if a Cell Is Reachable at a Given Time

Code

func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool {
    vert := abs(sy, fy)
    dist := vert + max(0, abs(sx, fx) - vert)
    if dist == 0 && t == 1 {
        return false
    }
    return dist <= t
}

func abs(x, y int) int {
    if x > y {
        return x - y
    }
    return y - x
}

1.85 - 2023-11-07 18:56:45 +0000 UTC

Design HashSet

Code

type MyHashSet struct {
    m map[int]struct{}
}


func Constructor() MyHashSet {
    return MyHashSet{map[int]struct{}{}}
}


func (this *MyHashSet) Add(key int)  {
    this.m[key] = struct{}{}
}


func (this *MyHashSet) Remove(key int)  {
    delete(this.m, key)
}


func (this *MyHashSet) Contains(key int) bool {
    _, ok := this.m[key]
    return ok
}


/**
 * Your MyHashSet object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Add(key);
 * obj.Remove(key);
 * param_3 := obj.Contains(key);
 */

1.86 - 2023-11-07 18:50:49 +0000 UTC

Merge Strings Alternately

Code

func mergeAlternately(word1 string, word2 string) string {
    var sb strings.Builder
    length1, length2 := len(word1), len(word2)
    for i := 0; i < max(length1, length2); i++ {
        if i == length1 {
            sb.WriteString(word2[i:length2])
            break
        }
        if i == length2 {
            sb.WriteString(word1[i:length1])
            break
        }
        sb.WriteByte(word1[i])
        sb.WriteByte(word2[i])
    }
    return sb.String()
}

1.87 - 2023-11-07 16:07:48 +0000 UTC

Eliminate Maximum Number of Monsters

Code

func eliminateMaximum(dist []int, speed []int) int {
    arrival := []float32{}
    length := len(dist)
    for i := 0; i < length; i++ {
        arrival = append(arrival, float32(dist[i]) / float32(speed[i]))
    }
    slices.Sort(arrival)
    ans := 0
    for i := 0; i < length; i++ {
        if arrival[i] <= float32(i) {
            break
        }
        ans += 1
    }
    return ans
}

1.88 - 2023-11-06 15:41:34 +0000 UTC

Design Circular Deque

Code

type MyCircularDeque struct {
    list []int
    size int
}


func Constructor(k int) MyCircularDeque {
    return MyCircularDeque{[]int{}, k}
}


func (this *MyCircularDeque) InsertFront(value int) bool {
    if this.IsFull() {
        return false
    }
    this.list = append([]int{value}, this.list...)
    return true
}


func (this *MyCircularDeque) InsertLast(value int) bool {
    if this.IsFull() {
        return false
    }
    this.list = append(this.list, value)
    return true
}


func (this *MyCircularDeque) DeleteFront() bool {
    if this.IsEmpty() {
        return false
    }
    this.list = this.list[1:]
    return true
}


func (this *MyCircularDeque) DeleteLast() bool {
    if this.IsEmpty() {
        return false
    }
    this.list = this.list[:len(this.list) - 1]
    return true
}


func (this *MyCircularDeque) GetFront() int {
    if this.IsEmpty() {
        return -1
    }
    return this.list[0]   
}


func (this *MyCircularDeque) GetRear() int {
    if this.IsEmpty() {
        return -1
    }
    return this.list[len(this.list) - 1]
}


func (this *MyCircularDeque) IsEmpty() bool {
    return len(this.list) == 0
}


func (this *MyCircularDeque) IsFull() bool {
    return len(this.list) == this.size
}


/**
 * Your MyCircularDeque object will be instantiated and called as such:
 * obj := Constructor(k);
 * param_1 := obj.InsertFront(value);
 * param_2 := obj.InsertLast(value);
 * param_3 := obj.DeleteFront();
 * param_4 := obj.DeleteLast();
 * param_5 := obj.GetFront();
 * param_6 := obj.GetRear();
 * param_7 := obj.IsEmpty();
 * param_8 := obj.IsFull();
 */

1.89 - 2023-11-06 11:57:33 +0000 UTC

Seat Reservation Manager

Code

type SeatManager struct {
    heap *binaryheap.Heap
}


func Constructor(n int) SeatManager {
    heap := binaryheap.NewWithIntComparator()
    for i := 1; i <= n; i++ {
        heap.Push(i)
    }
    return SeatManager{heap}
}


func (this *SeatManager) Reserve() int {
    val, _ := this.heap.Pop()
    return val.(int)
}


func (this *SeatManager) Unreserve(seatNumber int)  {
    this.heap.Push(seatNumber)
}


/**
 * Your SeatManager object will be instantiated and called as such:
 * obj := Constructor(n);
 * param_1 := obj.Reserve();
 * obj.Unreserve(seatNumber);
 */

1.90 - 2023-11-06 11:49:27 +0000 UTC

Seat Reservation Manager

Code

type SeatManager struct {
    seats []bool
}


func Constructor(n int) SeatManager {
    return SeatManager{make([]bool, n)}
}


func (this *SeatManager) Reserve() int {
    for i, num := range this.seats {
        if !num {
            this.seats[i] = true
            return i + 1
        }
    }
    return -1
}


func (this *SeatManager) Unreserve(seatNumber int)  {
    this.seats[seatNumber-1] = false
}


/**
 * Your SeatManager object will be instantiated and called as such:
 * obj := Constructor(n);
 * param_1 := obj.Reserve();
 * obj.Unreserve(seatNumber);
 */

1.91 - 2023-11-05 18:02:40 +0000 UTC

Serialize and Deserialize Binary Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type Codec struct {
    
}

func Constructor() Codec {
    return Codec{}
}

// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
    if root == nil {
        return ""
    }
    var buffer bytes.Buffer
    queue := []*TreeNode{root}
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            node := queue[i]
            if node != nil {
                buffer.WriteString(strconv.Itoa(node.Val))
                queue = append(queue, node.Left, node.Right)
            }
            buffer.WriteString(",")
        }
        queue = queue[length:]
    }
    ans := buffer.String()
    return ans[:len(ans)-1]
}

// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {    
    nodes := []*TreeNode{}
    for _, str := range strings.Split(data, ",") {
        if str == "" {
            nodes = append(nodes, nil)
        } else {
            num, _ := strconv.Atoi(str)
            nodes = append(nodes, &TreeNode{num, nil, nil})
        }
    }
    start := 0
    length := len(nodes)
    for _, node := range nodes {
        if node == nil {
            continue
        }
        left, right := 2 * start + 1, 2 * start + 2
        if left < length {
            node.Left = nodes[left]
        }
        if right < length {
            node.Right = nodes[right]
        }
        start++
    }
    return nodes[0]
}


/**
 * Your Codec object will be instantiated and called as such:
 * ser := Constructor();
 * deser := Constructor();
 * data := ser.serialize(root);
 * ans := deser.deserialize(data);
 */

1.92 - 2023-11-05 09:06:04 +0000 UTC

Find the Winner of an Array Game

Code

func getWinner(arr []int, k int) int {
    if k == 1 {
        return max(arr[0], arr[1])
    }
    length := len(arr)
    if k >= length {
        return slices.Max(arr)
    }
    curWinner, winCount := arr[0], 0
    for _, num := range arr[1:] {
        if curWinner > num {
            winCount++
        } else {
            curWinner = num
            winCount = 1
        }
        if winCount == k {
            return curWinner
        }
    }
    return curWinner
}

1.93 - 2023-11-05 09:01:59 +0000 UTC

Find the Winner of an Array Game

Code

func getWinner(arr []int, k int) int {
    curMax, winCount := arr[0], 0
    i, length := 1, len(arr)
    for {
        num := arr[i]
        if num > curMax {
            curMax = num
            winCount = 1
        } else {
            winCount++
        }
        if winCount == k {
            return curMax
        }
        i = (i + 1) % length
    }
    return -1
}

1.94 - 2023-11-04 10:31:04 +0000 UTC

Find Median from Data Stream

Code

type MaxHeap []int
func (m MaxHeap) Len() int { return len(m) }
func (m MaxHeap) Less(i, j int) bool { return m[i] > m[j] }
func (m MaxHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m *MaxHeap) Pop() interface{} {
    v := (*m)[len(*m)-1]
    *m = (*m)[:len(*m)-1]
    return v
}
func (m *MaxHeap) Push(v interface{}) { *m = append(*m, v.(int)) }
func (m MaxHeap) Top() int { return m[0] }

type MinHeap []int
func (m MinHeap) Len() int { return len(m) }
func (m MinHeap) Less(i, j int) bool { return m[i] < m[j] }
func (m MinHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m *MinHeap) Pop() interface{} {
    v := (*m)[len(*m)-1]
    *m = (*m)[:len(*m)-1]
    return v
}
func (m *MinHeap) Push(v interface{}) { *m = append(*m, v.(int)) }
func (m MinHeap) Top() int { return m[0] }

type MedianFinder struct {
    left MaxHeap
    right MinHeap    
}

func Constructor() MedianFinder {
    return MedianFinder{}    
}

func (mf *MedianFinder) AddNum(num int)  {
    if len(mf.left) + len(mf.right) == 0 {
        heap.Push(&(mf.left), num)
        return
    }
    for {
        if len(mf.left) < len(mf.right) {
            if num <= mf.right.Top() {
                heap.Push(&(mf.left), num)
                return
            } else {
                v := heap.Pop(&(mf.right))
                heap.Push(&(mf.left), v)
            }
        } else {
            if num >= mf.left.Top() {
                heap.Push(&(mf.right), num)
                return
            } else {
                v := heap.Pop(&(mf.left))
                heap.Push(&(mf.right), v)
            }
        }
    }
}

func (mf *MedianFinder) FindMedian() float64 {
    if len(mf.left) == len(mf.right) {
        return float64(mf.left.Top() + mf.right.Top()) / 2.0
    } else if len(mf.left) > len(mf.right) {
        return float64(mf.left.Top())
    } else {
        return float64(mf.right.Top())
    }   
}

1.95 - 2023-11-04 10:30:46 +0000 UTC

IPO

Code

type Project struct {
    profit, capital int
}

type IntHeap []int
func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
    n := len(profits)
    projects := make([]Project, n)
    for i := range profits {
        projects[i] = Project{profits[i], capital[i]}
    }
    sort.Slice(projects, func (i, j int) bool {
        return projects[i].capital < projects[j].capital
    })
    
    q := &IntHeap{}
    heap.Init(q)

    ptr := 0
    for i := 0; i < k; i++ {
        for ptr < n && projects[ptr].capital <= w {
            heap.Push(q, projects[ptr].profit)
            ptr++
        }
        if q.Len() == 0 {
            break
        }
        w += heap.Pop(q).(int)
    }
    return w
}

1.96 - 2023-11-04 10:30:28 +0000 UTC

Find Peak Element

Code

func findPeakElement(nums []int) int {
    left := 0
    right := len(nums) - 1
    
    for left < right {
        mid := left + (right - left) / 2
        
        if nums[mid] > nums[mid+1] {
            // The peak is in the left half
            right = mid
        } else {
            // The peak is in the right half
            left = mid + 1
        }
    }
    
    return left
}

1.97 - 2023-11-04 10:30:08 +0000 UTC

Merge k Sorted Lists

Code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeKLists(lists []*ListNode) *ListNode {
    n:=len(lists)
    if n==0{
        return nil
    }
    curr:=lists[0]
    if n==1{
        return curr
    }
    for i:=1;i<n;i++{
        curr=mergeList(curr,lists[i])
    }
    return curr
}

func mergeList(l1,l2 *ListNode) *ListNode {
    head:=&ListNode{}
    curr:=head
    for l1!=nil && l2!=nil{
        if l1.Val<l2.Val{
            curr.Next=l1
            l1=l1.Next
            curr=curr.Next
        }else{
            curr.Next=l2
            l2=l2.Next
            curr=curr.Next
        }
    }
    if l1 != nil {
        curr.Next = l1
    } else if l2 != nil {
        curr.Next = l2
    }
    return head.Next
}

1.98 - 2023-11-04 10:29:52 +0000 UTC

Construct Quad Tree

Code

/**
 * Definition for a QuadTree node.
 * type Node struct {
 *     Val bool
 *     IsLeaf bool
 *     TopLeft *Node
 *     TopRight *Node
 *     BottomLeft *Node
 *     BottomRight *Node
 * }
 */

func construct(grid [][]int) *Node {
	var dfs func(y0, x0, width int) *Node
	dfs = func(y0, x0, width int) *Node {
		if width == 1 {
			return &Node{
				Val:    grid[y0][x0] == 1,
				IsLeaf: true,
			}
		}

		w := width / 2
		topLeft := dfs(y0, x0, w)
		topRight := dfs(y0, x0+w, w)
		bottomLeft := dfs(y0+w, x0, w)
		bottomRight := dfs(y0+w, x0+w, w)
		var node *Node

		if topLeft.Val == topRight.Val && bottomLeft.Val == bottomRight.Val && topLeft.Val == bottomLeft.Val &&
			topLeft.IsLeaf && topRight.IsLeaf && bottomLeft.IsLeaf && bottomRight.IsLeaf {
			node = &Node{
				Val:    topLeft.Val,
				IsLeaf: true,
			}
		} else {
			node = &Node{
				Val:         true,
				IsLeaf:      false,
				TopLeft:     topLeft,
				TopRight:    topRight,
				BottomLeft:  bottomLeft,
				BottomRight: bottomRight,
			}
		}
		return node
	}
	return dfs(0, 0, len(grid))
}

1.99 - 2023-11-04 10:29:35 +0000 UTC

N-Queens II

Code

func totalNQueens(n int) int {
    sCol:=make([]bool,n)
    sD1:=make([]bool,2*n)
    sD2:=make([]bool,2*n)
    return helper(0,n,sCol,sD1,sD2)
}
func helper(r,n int,sCol,sD1,sD2 []bool) int{
    if r==n{
        return 1
    }
    res:=0
    for i:=0; i < n; i++ {
        if !sCol[i] && !sD1[i+r] && !sD2[(r-i)+n]{
          // board[r][i]=true
            sCol[i]=true
            sD1[i+r]=true
            sD2[(r-i)+n]=true
            res=res+helper(r+1,n,sCol,sD1,sD2)
          //  board[r][i]=false
            sCol[i]=false
            sD1[i+r]=false
            sD2[(r-i)+n]=false
        }
    }
    return res
}

1.100 - 2023-11-04 10:29:17 +0000 UTC

Word Search II

Code

type Node struct {
	children [26]*Node
	word     string
}

func (n *Node) Insert(word string) {
	cur := n
	for _, c := range word {
		idx := c - 'a'
		if cur.children[idx] == nil {
			cur.children[idx] = &Node{}
		}
		cur = cur.children[idx]
	}
	cur.word = word
}

func (n *Node) IsEmpty() bool {
	for _, child := range n.children {
		if child != nil {
			return false
		}
	}
	return true
}

func (n *Node) Remove(word string) bool {
	if len(word) == 0 {
		n.word = ""
		return n.IsEmpty()
	}
	child := n.children[word[0]-'a']
	if child.Remove(word[1:]) {
		n.children[word[0]-'a'] = nil
		return n.IsEmpty()
	}
	return false
}

func dfs(board [][]byte, r, c int, root, cur *Node, res *[]string) {
	rc := board[r][c]
	board[r][c] = 0
    
	if cur.word != "" {
		*res = append(*res, cur.word)
		root.Remove(cur.word)
	}
	ds := [5]int{0, 1, 0, -1, 0}
	for i := 0; i < len(ds)-1; i++ {
		dr, dc := r+ds[i], c+ds[i+1]
		if dr < 0 || dr >= len(board) || dc < 0 || dc >= len(board[0]) {
			continue
		}
		b := board[dr][dc]
		if b == 0 || cur.children[b-'a'] == nil {
			continue
		}
		dfs(board, dr, dc, root, cur.children[b-'a'], res)
	}
	board[r][c] = rc
}

func findWords(board [][]byte, words []string) []string {
	m, n := len(board), len(board[0])
	res, trie, has := []string{}, &Node{}, map[string]bool{}

	for r := 0; r < m; r++ {
		for c := 0; c < n-1; c++ {
			p := string(board[r][c]) + string(board[r][c+1])
			has[p] = true
		}
	}
	for r := 0; r < m-1; r++ {
		for c := 0; c < n; c++ {
			p := string(board[r][c]) + string(board[r+1][c])
			has[p] = true
		}
	}
	for _, word := range words {
		valid := true
		for i := 0; i < len(word)-1; i++ {
			a, b := string(word[i]), string(word[i+1])
			if !has[a+b] && !has[b+a] {
				valid = false
				break
			}
		}
		if valid {
			trie.Insert(word)
		}
	}
	for r := 0; r < m; r++ {
		for c := 0; c < n; c++ {
			b := board[r][c]
			if trie.children[b-'a'] != nil {
				dfs(board, r, c, trie, trie.children[b-'a'], &res)
			}
		}
	}
	return res
}

1.101 - 2023-11-04 10:28:50 +0000 UTC

Word Ladder

Code

func ladderLength(beginWord string, endWord string, wordList []string) int {
    
    set := make(map[string]struct{}, len(wordList))
    
    present := false
    
    for _, v := range wordList {
        if endWord == v {
            present = true
        } 
        
        set[v] = struct{}{} 
    }
    
    if !present {
        return 0
    }
    
    set[beginWord] = struct{}{}
    q := []string{beginWord}
    
    depth := 1
    breadth := 0
    
    breadth = len(q)
    
    for ;breadth > 0; {
        s := q[0]
        
        if s == endWord {
            return depth
        }
        
        for i:='a'; i <= 'z'; i += 1 {
                        
            for j := 0; j<len(s); j++ {
 
                if rune(s[j]) != i {
                    
                    temp := s[:j] + string(i) + s[j+1:]
                    if _, ok := set[temp]; !ok {
                        continue
                    }
                    
                    q = append(q, temp)
                    delete(set, s)
                }
            }
        }
        
        q = q[1:]
        
        breadth -= 1
        if breadth == 0 {
            breadth = len(q)
            depth += 1
        }
    }
    
    return 0 
}

1.102 - 2023-11-04 10:28:04 +0000 UTC

Course Schedule II

Code

func findOrder(numCourses int, prerequisites [][]int) []int {
    //build the graph
    graph := make([][]int,numCourses)
    in_degree := make([]int,numCourses)
    for _,v := range prerequisites{
        graph[v[1]] = append(graph[v[1]], v[0])
        in_degree[v[0]]++
    }

    frontier := []int{}
    for i,v := range in_degree{
        if v==0{
            frontier = append(frontier,i)
        }
    }

    result := []int{}
    for len(frontier)!=0{
        cur := frontier[0]
        frontier = frontier[1:]
        result = append(result,cur)
        for _,v := range graph[cur]{
            in_degree[v]--
            if in_degree[v]==0{
                frontier = append(frontier,v)
            }
        }
    }

    if len(result)==numCourses{
        return result
    }
    return []int{}
}

1.103 - 2023-11-04 10:27:48 +0000 UTC

Binary Tree Maximum Path Sum

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxPathSum(root *TreeNode) int {
    ans := -1 << 63
    maxPath(root, &ans)
    return ans
}

func maxPath(root *TreeNode, ans *int) int {
    if root == nil {
        return 0
    }
    leftPathSum := maxPath(root.Left, ans)
    rightPathSum := maxPath(root.Right, ans)
    *ans = max(*ans, leftPathSum + rightPathSum + root.Val)
    return max(max(leftPathSum+root.Val, rightPathSum+root.Val), 0)
}

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

1.104 - 2023-11-04 10:27:29 +0000 UTC

Construct Binary Tree from Inorder and Postorder Traversal

Code

func buildTree(inorder []int, postorder []int) *TreeNode {
	n := len(postorder)
	if n == 0 {
		return nil
	}

	pivotId := 0
	for pivotId < n && inorder[pivotId] != postorder[n-1] {
		pivotId++
	}

	root := new(TreeNode)
	root.Val = postorder[n-1]
	root.Left = buildTree(inorder[:pivotId], postorder[:pivotId])
	root.Right = buildTree(inorder[pivotId+1:], postorder[pivotId:n-1])
	return root
}

1.105 - 2023-11-04 10:27:12 +0000 UTC

Construct Binary Tree from Preorder and Inorder Traversal

Code

func buildTree(preorder []int, inorder []int) *TreeNode {
	n := len(inorder)

	if n == 0 {
		return nil
	}

	pv := preorder[0]
	pi := 0
	for pi < n && inorder[pi] != pv {
		pi++
	}

	ans := new(TreeNode)
	ans.Val = pv
	ans.Left = buildTree(preorder[1:], inorder[:pi])
	ans.Right = buildTree(preorder[1+pi:], inorder[pi+1:])

	return ans
}

1.106 - 2023-11-04 10:26:43 +0000 UTC

Reverse Nodes in k-Group

Code

func reverseKGroup(head *ListNode, k int) *ListNode {
	node, cnt := head, 0
	for cnt < k {
		if node == nil {
			return head
		}
		node = node.Next
		cnt++
	}

	prev := reverseKGroup(node, k)
	for cnt > 0 {
		next := head.Next
		head.Next = prev
		prev = head
		head = next
		cnt--
	}

	return prev
}

1.107 - 2023-11-04 10:25:42 +0000 UTC

Minimum Number of Arrows to Burst Balloons

Code

func findMinArrowShots(points [][]int) int {
	// greedy solution
	sort.Slice(points, func(i, j int) bool {
		return points[i][1] < points[j][1]
	})
	count := 1
	end := points[0][1]
	for i := 1; i < len(points); i++ {
		if points[i][0] > end {
			count++
			end = points[i][1]
		}
	}
	return count
}

1.108 - 2023-11-04 10:25:15 +0000 UTC

Minimum Window Substring

Code

func minWindow(s string, t string) string {
    m := len(s)
    n := len(t)
    
    if m == 0 || n == 0 || m < n {
        return ""
    }

    dict := make(map[byte]int)
    for i := 0; i < n; i++ {
        dict[t[i]]++
    }
    
    // required unique chars
    required := len(dict)
    actual := 0
    window := make(map[byte]int)
    minSize := math.MaxInt64
    start := 0
    left, right := 0, 0
    
    for end := 0; end < m; end++ {
        c := s[end]
        window[c]++
        
        if value, ok := dict[c]; ok {
            if value == window[c] {
                actual++
            }
        }
        
        for start <= end && actual == required {
            size := end-start+1
            if size < minSize {
                minSize = size
                left = start
                right = end
            }
            
            rc := s[start]
            window[rc]--
            if value, ok := dict[rc]; ok {
                if value > window[rc] {
                    actual--
                }
            }
            start++
        }
    }
    
    if minSize == math.MaxInt64 {
        return ""
    }
    return s[left:right+1]
}

1.109 - 2023-11-04 10:24:58 +0000 UTC

Substring with Concatenation of All Words

Code

func findSubstring(s string, words []string) []int {
    
    wordLen := len(words[0])
    totalWords := len(words)
    mem := make(map[string]int, totalWords)
    
    
    for _, str := range words {
        mem[str] += 1
    }
    
    temp := make(map[string]int, totalWords)
    var found bool
    result := make([]int, 0)
    
    for i:=0; i + wordLen*totalWords <= len(s);  {
            
        found = true
        temp = make(map[string]int, totalWords)

        for j := i; j < i + wordLen*totalWords; j += wordLen {
            if _, ok := mem[ s[j:j+wordLen] ]; ok {
                temp[ s[j:j+wordLen] ] += 1
            } else {
                found = false
                break
            }
        }

        if found {
            for key, _ := range mem {
                if val, ok := temp[key]; !ok || val != mem[key]{
                    i++
                    found = false
                    break
                }
            }

            if found {
                result = append(result, i)
                i += 1    
            }

        } else {
            i++
        }
    }
    
    return result
    
}

1.110 - 2023-11-04 10:23:30 +0000 UTC

Insert Interval

Code

func insert(intervals [][]int, new []int) [][]int {
    n := len(intervals)
    i := sort.Search(n, func(i int) bool { return intervals[i][0] > new[0] })
    j := sort.Search(n, func(j int) bool { return intervals[j][1] > new[1] })
    if i >= 1 && new[0] <= intervals[i-1][1] {
        new[0] = intervals[i-1][0]
        i--
    }
    if j < n && new[1] >= intervals[j][0] {
        new[1] = intervals[j][1]
        j++
    }
    return append(intervals[:i], append([][]int{new}, intervals[j:]...)...)
}

1.111 - 2023-11-04 10:22:41 +0000 UTC

Basic Calculator

Code

func calculate(s string) int {
	result, _ := calculateFrom(s, 0)
	return result
}

func calculateFrom(s string, idFrom int) (result, idEnd int) {
	result, currNum, sign := 0, 0, 1

	for idEnd = idFrom; idEnd < len(s) && s[idEnd] != ')'; idEnd++ {
		switch {
		case s[idEnd] >= '0':
			currNum = currNum*10 + int(s[idEnd]-'0')
		case s[idEnd] == '(':
			currNum, idEnd = calculateFrom(s, idEnd+1)
		case s[idEnd] == '-' || s[idEnd] == '+':
			result, currNum = result+currNum*sign, 0
			sign = 44 - int(s[idEnd]) // '-'=45; '+'=43
		}
	}

	return result + currNum*sign, idEnd
}

1.112 - 2023-11-04 07:36:18 +0000 UTC

Last Moment Before All Ants Fall Out of a Plank

Code


func getLastMoment(n int, left []int, right []int) int {
    return max(slices.Max(append(left, 0)), n - slices.Min(append(right, n)))
}

1.113 - 2023-11-04 07:30:12 +0000 UTC

Last Moment Before All Ants Fall Out of a Plank

Code

func getLastMoment(n int, left []int, right []int) int {
    maxLeft := 0
    for _, val := range left {
        if val > maxLeft {
            maxLeft = val
        }
    }
    minRight := n
    for _, val := range right {
        if val < minRight {
            minRight = val
        }
    }
    return max(maxLeft, n - minRight)
}

1.114 - 2023-11-04 07:29:26 +0000 UTC

Last Moment Before All Ants Fall Out of a Plank

Code

func getLastMoment(n int, left []int, right []int) int {
    maxLeft := 0
    for _, val := range left {
        if val > maxLeft {
            maxLeft = val
        }
    }
    
    minRight := n
    for _, val := range right {
        if val < minRight {
            minRight = val
        }
    }
    return max(maxLeft, n - minRight)
}

1.115 - 2023-11-03 12:20:27 +0000 UTC

Kth Smallest Element in a BST

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func kthSmallest(root *TreeNode, k int) int {
    heap := binaryheap.NewWithIntComparator()
    queue := []*TreeNode{root}

    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            node := queue[i]
            if node == nil {
                continue
            }
            heap.Push(node.Val)
            queue = append(queue, node.Left, node.Right)
        }
        queue = queue[length:]
    }
    var answer any
    for i := 0; i < k; i++ {
        answer, _ = heap.Pop()
    }
    return answer.(int)
}

1.116 - 2023-11-03 09:40:06 +0000 UTC

Flatten Binary Tree to Linked List

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func flatten(root *TreeNode)  {
    if root == nil {
        return
    }
    right := root.Right
    root.Right = nil
    list := &TreeNode{0, nil, nil}
    listTail := flattenNode(root, list)
    if right != nil {
        flattenNode(right, listTail)
    }
}

func flattenNode(node, listTail *TreeNode) *TreeNode {
    left, right := node.Left, node.Right
    node.Left, node.Right = nil, nil
    listTail.Right = node
    listTail = listTail.Right
    if left != nil {
        listTail = flattenNode(left, listTail)
    }
    if right != nil {
        listTail = flattenNode(right, listTail)
    }
    return listTail
}

1.117 - 2023-11-03 09:14:46 +0000 UTC

Build an Array With Stack Operations

Code

func buildArray(target []int, n int) []string {
    ops := []string{}
    length := len(target)
    matchNext, matchNextVal := 0, target[0]
    for i := 1; i <= n; i++ {
        if i == matchNextVal {
            ops = append(ops, "Push")
            matchNext += 1
            if matchNext == length {
                break
            }
            matchNextVal = target[matchNext]
        } else {
            ops = append(ops, "Push", "Pop")
        }
    }
    return ops
}

1.118 - 2023-11-03 09:13:05 +0000 UTC

Build an Array With Stack Operations

Code

func buildArray(target []int, n int) []string {
    ops := []string{}
    length := len(target)
    matchNext := 0
    for i := 1; i <= n; i++ {
        if matchNext == length {
            break
        }
        ops = append(ops, "Push")
        if i == target[matchNext] {
            matchNext += 1
        } else {
            ops = append(ops, "Pop")
        }
    }
    return ops
}

1.119 - 2023-11-02 11:33:34 +0000 UTC

Sort List

Code


func sortList(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	if head.Next.Next == nil {
		a := head
		b := head.Next
		if a.Val <= b.Val {
			a.Next = b
			b.Next = nil
			return a
		} else {
			b.Next = a
			a.Next = nil
			return b
		}
	}
	slow := head
	fast := head
	for fast != nil && fast.Next != nil {
		slow = slow.Next
		fast = fast.Next.Next
	}
	nextList := slow.Next
	slow.Next = nil
	list1 := sortList(head)
	list2 := sortList(nextList)
	dummy := &ListNode{Val: -1, Next: nil}
	it := dummy
	for list1 != nil && list2 != nil {
		if list1.Val <= list2.Val {
			it.Next = list1
			list1 = list1.Next
		} else {
			it.Next = list2
			list2 = list2.Next
		}
		it = it.Next
	}
	if list1 != nil {
		it.Next = list1
	} else {
		it.Next = list2
	}
	return dummy.Next
}

1.120 - 2023-11-02 10:32:46 +0000 UTC

Count Nodes Equal to Average of Subtree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func averageOfSubtree(root *TreeNode) int {
    _, _, answer := getAverage(root)
    return answer
}

func getAverage(root *TreeNode) (int, int, int) {
    if root == nil {
        return 0, 0, 0
    }
    sum, count, validNodes := root.Val, 1, 0
    leftSum, leftCount, leftValidNodes := getAverage(root.Left)
    rightSum, rightCount, rightValidNodes := getAverage(root.Right)
    validNodes += leftValidNodes + rightValidNodes
    sum += leftSum + rightSum
    count += leftCount + rightCount
    if sum / count == root.Val {
        validNodes += 1
    }
    return sum, count, validNodes
}

1.121 - 2023-11-01 12:59:19 +0000 UTC

Sum Root to Leaf Numbers

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type queueItem struct {
    node *TreeNode
    sum int
}
func sumNumbers(root *TreeNode) int {
    if root == nil {
        return 0
    }
    queue := []queueItem{queueItem{root, 0}}
    sum := 0
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            item := queue[i]
            if item.node == nil {
                continue
            }
            left, right, newVal := item.node.Left, item.node.Right, item.node.Val + item.sum * 10
            if left == nil && right == nil {
                sum += newVal
            } else {
                queue = append(queue, queueItem{left, newVal}, queueItem{right, newVal})
            }
        }
        queue = queue[length:]
    }
    return sum
}

1.122 - 2023-11-01 12:51:19 +0000 UTC

Sum Root to Leaf Numbers

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumNumbers(root *TreeNode) int {
    return getSum(root, 0)
}

func getSum(root *TreeNode, parentVal int) int {
    if root == nil {
        return 0
    }
    newVal := root.Val + parentVal * 10
    if root.Left == nil && root.Right == nil {
        return newVal
    }
    return getSum(root.Left, newVal) + getSum(root.Right, newVal)
}

1.123 - 2023-11-01 12:01:54 +0000 UTC

Lowest Common Ancestor of a Binary Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
    if root == nil {
		return nil
	}
    if root == p || root == q {
		return root
	}
    left, right := lowestCommonAncestor(root.Left, p, q), lowestCommonAncestor(root.Right, p, q)
    if left != nil && right != nil {
		return root
	}
	if left != nil {
		return left
	}
	return right
}

1.124 - 2023-11-01 12:00:05 +0000 UTC

Lowest Common Ancestor of a Binary Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
    isAncestorMap := map[int][2]bool{}
    dfs(root, p, q, isAncestorMap)
    isAncestor := func (node *TreeNode) bool {
        if node == nil {
            return false
        }
        hasNodes := isAncestorMap[node.Val]
        return hasNodes[0] && hasNodes[1]
    }

    for {
        left, right := root.Left, root.Right
        if isAncestor(left) {
            root = left
        } else if isAncestor(right) {
            root = right
        } else {
            break
        }
    }
    return root
}

func dfs(root, p, q *TreeNode, isAncestorMap map[int][2]bool) (bool, bool)  {
    if root == nil {
        return false, false
    }
    hasPLeft, hasQLeft := dfs(root.Left, p, q, isAncestorMap)
    hasPRight, hasQRight := dfs(root.Right, p, q, isAncestorMap)
    hasP, hasQ := hasPLeft || hasPRight, hasQLeft || hasQRight
    if root == p {
        hasP = true
    }
    if root == q {
        hasQ = true
    }
    isAncestorMap[root.Val] = [2]bool{hasP, hasQ}
    return hasP, hasQ
}

1.125 - 2023-11-01 09:34:06 +0000 UTC

Find Mode in Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findMode(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }
    counter := map[int]int{}
    queue := []*TreeNode{root}
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            node := queue[i]
            if node == nil {
                continue
            }
            left, right, val := node.Left, node.Right, node.Val
            if _, ok := counter[val]; ok {
                counter[val] +=  1
            } else {
                counter[val] = 1
            }
            queue = append(queue, left, right)
        }
        queue = queue[length:]
    }
    maxCount, answer := 0, []int{}
    for key, count := range counter {
        if count < maxCount {
            continue
        }
        if count > maxCount {
            answer = answer[:0]
            maxCount = count
        }
        answer = append(answer, key)
    }
    return answer
}

1.126 - 2023-11-01 09:32:26 +0000 UTC

Find Mode in Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findMode(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }
    counter := map[int]int{}
    queue := []*TreeNode{root}
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            node := queue[i]
            if node == nil {
                continue
            }
            if val, ok := counter[node.Val]; ok {
                counter[node.Val] = val + 1
            } else {
                counter[node.Val] = 1
            }
            queue = append(queue, node.Left, node.Right)
        }
        queue = queue[length:]
    }
    maxCount, answer := 0, []int{}
    for key, count := range counter {
        if count < maxCount {
            continue
        }
        if count > maxCount {
            answer = answer[:0]
            maxCount = count
        }
        answer = append(answer, key)
    }
    return answer
}

1.127 - 2023-11-01 09:28:17 +0000 UTC

Find Mode in Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findMode(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }
    counter := map[int]int{}
    dfs(root, counter)
    maxCount, answer := 0, []int{}
    for key, count := range counter {
        if count < maxCount {
            continue
        }
        if count > maxCount {
            answer = answer[:0]
            maxCount = count
        }
        answer = append(answer, key)
    }
    return answer
}

func dfs(root *TreeNode, counter map[int]int) {
    if root == nil {
        return
    }
    if _, ok := counter[root.Val]; ok {
        counter[root.Val] += 1
    } else {
        counter[root.Val] = 1
    }
    dfs(root.Left, counter)
    dfs(root.Right, counter)
}

1.128 - 2023-11-01 09:20:58 +0000 UTC

Find Mode in Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findMode(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }
    counter := map[int]int{}
    queue := []*TreeNode{root}
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            node := queue[i]
            if _, ok := counter[node.Val]; ok {
                counter[node.Val] += 1
            } else {
                counter[node.Val] = 1
            }
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        queue = queue[length:]
    }
    maxCount, answer := 0, []int{}
    for key, count := range counter {
        if count < maxCount {
            continue
        }
        if count > maxCount {
            answer = answer[:0]
            maxCount = count
        }
        answer = append(answer, key)
    }
    return answer
}

1.129 - 2023-10-31 16:12:05 +0000 UTC

Validate Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
type queueItem struct  {
    node *TreeNode
    max *int
    min *int
}

func isValidBST(root *TreeNode) bool {
    queue := []queueItem{queueItem{root, nil, nil}}
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            item := queue[i]
            if item.node == nil {
                continue
            }
            node := item.node
            if (item.max != nil && node.Val >= *item.max) || (item.min != nil && node.Val <= *item.min) {
                return false
            }
            queue = append(
                queue, 
                queueItem{node.Left, &node.Val, item.min}, 
                queueItem{node.Right, item.max, &node.Val},
            )
        }
        queue = queue[length:]
    }
    return true
}

1.130 - 2023-10-31 16:11:41 +0000 UTC

Validate Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
type queueItem struct  {
    node *TreeNode
    max *int
    min *int
}

func isValidBST(root *TreeNode) bool {
    queue := []queueItem{queueItem{root, nil, nil}}
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            item := queue[i]
            if item.node == nil {
                continue
            }
            node := item.node
            if (item.max != nil && node.Val >= *item.max) || (item.min != nil && node.Val <= *item.min) {
                return false
            }
            queue = append(
                queue, 
                queueItem{node.Left, &node.Val, item.min}, 
                queueItem{node.Right, item.max, &node.Val},
            )
        }
        queue = queue[length:]
    }
    return true
}

1.131 - 2023-10-31 15:59:17 +0000 UTC

Validate Binary Search Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isValidBST(root *TreeNode) bool {
    if root == nil {
        return false
    }
    return dfs(root.Left, &root.Val, nil) && dfs(root.Right, nil, &root.Val)
}

func dfs(root *TreeNode, max *int, min *int) bool {
    if root == nil {
        return true
    }
    if (max != nil && root.Val >= *max) || (min != nil && root.Val <= *min) {
        return false
    }
    return dfs(root.Left, &root.Val, min) && dfs(root.Right, max, &root.Val)
}

1.132 - 2023-10-31 15:18:34 +0000 UTC

Maximum Sum Circular Subarray

Code

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

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func maxSubarraySumCircular(nums []int) int {
    var (
        max_sum_ending_here = 0
        min_sum_ending_here = 0
        max_sum_so_far = math.MinInt
        min_sum_so_far = math.MaxInt
        total = 0
    )
    for i := 0; i < len(nums); i++ {
        num := nums[i]
        total += num
        max_sum_ending_here += num
        min_sum_ending_here += num
        max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
        min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
        max_sum_ending_here = max(max_sum_ending_here, 0)
        min_sum_ending_here = min(min_sum_ending_here, 0)
    }
    if max_sum_so_far < 0 {
        return max_sum_so_far
    }
    return max(max_sum_so_far, total - min_sum_so_far)
}

1.133 - 2023-10-31 15:15:28 +0000 UTC

Maximum Sum Circular Subarray

Code

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

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func maxSubarraySumCircular(nums []int) int {
    var (
        max_sum_ending_here = 0
        min_sum_ending_here = 0
        max_sum_so_far = math.MinInt
        min_sum_so_far = math.MaxInt
        total = 0
    )
    for i := 0; i < len(nums); i++ {
        total += nums[i]
        max_sum_ending_here += nums[i]
        min_sum_ending_here += nums[i]
        max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
        min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
        max_sum_ending_here = max(max_sum_ending_here, 0)
        min_sum_ending_here = min(min_sum_ending_here, 0)
    }
    if max_sum_so_far < 0 {
        return max_sum_so_far
    }
    return max(max_sum_so_far, total - min_sum_so_far)
}

1.134 - 2023-10-31 15:13:57 +0000 UTC

Maximum Sum Circular Subarray

Code

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

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func maxSubarraySumCircular(nums []int) int {
    var max_sum_ending_here int = 0
    var min_sum_ending_here int = 0
    var max_sum_so_far int = math.MinInt
    var min_sum_so_far int = math.MaxInt
    var total = 0
    for i := 0; i < len(nums); i++ {
        total += nums[i]
        max_sum_ending_here += nums[i]
        min_sum_ending_here += nums[i]
        max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
        min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
        max_sum_ending_here = max(max_sum_ending_here, 0)
        min_sum_ending_here = min(min_sum_ending_here, 0)
    }
    if max_sum_so_far < 0 {
        return max_sum_so_far
    }
    return max(max_sum_so_far, total - min_sum_so_far)
}

1.135 - 2023-10-31 08:33:38 +0000 UTC

Find The Original Array of Prefix Xor

Code

func findArray(pref []int) []int {
    prev := pref[0]
    for i := 1; i < len(pref); i++ {
        cur := pref[i]
        prev, pref[i] = cur, prev ^ cur 
    }
    return pref
}

1.136 - 2023-10-31 08:32:41 +0000 UTC

Find The Original Array of Prefix Xor

Code

func findArray(pref []int) []int {
    prev := pref[0]
    for i := 1; i < len(pref); i++ {
        prev, pref[i] = pref[i], prev ^ pref[i] 
    }
    return pref
}

1.137 - 2023-10-30 13:28:30 +0000 UTC

Trapping Rain Water

Code

func trap(height []int) int {
    left, right := 0, len(height) - 1
    res := 0
    leftMax, rightMax := 0, 0

    for left < right {
        if height[left] < height[right] {
            if height[left] >= leftMax {
                leftMax = height[left]
            } else {
                res += (leftMax-height[left])
            }
            left++
        } else {
            if height[right] >= rightMax {
                rightMax = height[right]
            } else {
                res += (rightMax-height[right])
            }
            right--
        }
    }

    return res
}

1.138 - 2023-10-30 13:03:18 +0000 UTC

Minimum Genetic Mutation

Code

func minMutation(startGene string, endGene string, bank []string) int {
    if startGene == endGene {
        return 0
    }

    bank = append(bank, startGene)

    isMut := func (gene1 string, gene2 string) bool {
        foundDiff := false
        for i := 0; i < len(gene1); i++ {
            if gene1[i] == gene2[i] {
                continue
            }
            if foundDiff {
                return false
            }
            foundDiff = true
        } 
        return foundDiff
    }

    graph := map[string][]string{}

    for i, gene1 := range bank {
        for _, gene2 := range bank[i+1:] {
            if !isMut(gene1, gene2) {
                continue
            }
            if _, ok := graph[gene1]; !ok {
                graph[gene1] = []string{}
            }
            if _, ok := graph[gene2]; !ok {
                graph[gene2] = []string{}
            }
            graph[gene1] = append(graph[gene1], gene2)
            graph[gene2] = append(graph[gene2], gene1)
        }
    }

    queue, ok := graph[endGene]
    if !ok {
        return -1
    }
    delete(graph, endGene)
    num := 1
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            gene := queue[i]
            muts, ok := graph[gene]
            if !ok {
                continue
            }
            if gene == startGene {
                return num 
            }
            delete(graph, gene)
            queue = append(queue, muts...)
        }
        num += 1
        queue = queue[length:]
    }

    return -1
}

1.139 - 2023-10-30 12:58:41 +0000 UTC

Minimum Genetic Mutation

Code

func minMutation(startGene string, endGene string, bank []string) int {
    if startGene == endGene {
        return 0
    }

    bank = append(bank, startGene)

    isMut := func (gene1 string, gene2 string) bool {
        foundDiff := false
        for i := 0; i < len(gene1); i++ {
            if gene1[i] == gene2[i] {
                continue
            }
            if foundDiff {
                return false
            }
            foundDiff = true
        } 
        return foundDiff
    }

    graph := map[string][]string{}

    for i, gene1 := range bank {
        for _, gene2 := range bank[i+1:] {
            if !isMut(gene1, gene2) {
                continue
            }
            if _, ok := graph[gene1]; !ok {
                graph[gene1] = []string{}
            }
            if _, ok := graph[gene2]; !ok {
                graph[gene2] = []string{}
            }
            graph[gene1] = append(graph[gene1], gene2)
            graph[gene2] = append(graph[gene2], gene1)
        }
    }

    queue, ok := graph[endGene]
    if !ok {
        return -1
    }
    visited := map[string]struct{}{endGene: struct{}{}}
    num := 1
    for length := len(queue); length > 0; length = len(queue) {
        for i := 0; i < length; i++ {
            gene := queue[i]
            if _, ok := visited[gene]; ok {
                continue
            }
            if gene == startGene {
                return num 
            }
            visited[gene] = struct{}{}
            queue = append(queue, graph[gene]...)
        }
        num += 1
        queue = queue[length:]
    }

    return -1
}

1.140 - 2023-10-30 11:32:47 +0000 UTC

Binary Tree Zigzag Level Order Traversal

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func zigzagLevelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }

    queue, answer := []*TreeNode{root}, [][]int{}
    ltr := true

    for length := len(queue); length != 0; length = len(queue) {
        answerRow := []int{}
        for i := 0; i < length; i++ {
            node := queue[i]
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            answerRow = append(answerRow, node.Val)
        }
        if !ltr {
            slices.Reverse(answerRow)
        }
        queue = queue[length:]
        ltr = !ltr
        answer = append(answer, answerRow)
    }

    return answer
}

1.141 - 2023-10-30 11:31:36 +0000 UTC

Binary Tree Zigzag Level Order Traversal

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func zigzagLevelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }

    queue, answer := []*TreeNode{root}, [][]int{}
    ltr := true

    for length := len(queue); length != 0; length = len(queue) {
        answerRow := []int{}
        for i := 0; i < length; i++ {
            node := queue[i]
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            if ltr {
                answerRow = append(answerRow, node.Val)
            } else {
                answerRow = append([]int{node.Val}, answerRow...)
            }
        }
        queue = queue[length:]
        ltr = !ltr
        answer = append(answer, answerRow)
    }

    return answer
}

1.142 - 2023-10-30 11:14:48 +0000 UTC

Binary Tree Zigzag Level Order Traversal

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func zigzagLevelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }

    queue, answer := []*TreeNode{root}, [][]int{}
    leftToRight := true

    for length := len(queue); length != 0; length = len(queue) {
        answerRow := []int{}

        for i := 0; i < length; i++ {
            node := queue[0]
            queue = queue[1:]

            answerRow = append(answerRow, node.Val)
            if left := node.Left; left != nil {
                queue = append(queue, left)
            }
            if right := node.Right; right != nil {
                queue = append(queue, right)
            }
        }
        if !leftToRight {
            slices.Reverse(answerRow)
        }
        leftToRight = !leftToRight
        answer = append(answer, answerRow)
    }

    return answer
}

1.143 - 2023-10-30 10:59:23 +0000 UTC

Binary Tree Level Order Traversal

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    queue, answer := []*TreeNode{root}, [][]int{}

    for length := len(queue); length != 0; length = len(queue) {
        answerRow := []int{}
        for i := 0; i < length; i++ {
            node := queue[0]
            queue = queue[1:]
            if node == nil {
                continue
            }
            answerRow = append(answerRow, node.Val)
            queue = append(queue, node.Left, node.Right)
        }
        if len(answerRow) != 0 {
            answer = append(answer, answerRow)
        }
    }

    return answer
}

1.144 - 2023-10-30 10:51:15 +0000 UTC

Binary Tree Level Order Traversal

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }

    stack, answer := []*TreeNode{root}, [][]int{}

    for length := len(stack); length != 0; length = len(stack) {
        answerRow := []int{}
        for i := 0; i < length; i++ {
            node := stack[0]
            answerRow = append(answerRow, node.Val)
            stack = stack[1:]
            if left := node.Left; left != nil {
                stack = append(stack, node.Left)
            }
            if right := node.Right; right != nil {
                stack = append(stack, node.Right)
            }
        }
        answer = append(answer, answerRow)
    }

    return answer
}

1.145 - 2023-10-30 10:39:35 +0000 UTC

Binary Tree Right Side View

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }

    queue, answer := []*TreeNode{root}, []int{}

    for length := len(queue); length != 0; length = len(queue) {
        for i := 0; i < length; i++ {
            node := queue[0]
            queue = queue[1:]
            if i == length - 1 {
                answer = append(answer, node.Val)
            }
            if left := node.Left; left != nil {
                queue = append(queue, left)
            }
            if right := node.Right; right != nil {
                queue = append(queue, right)
            }
        }
    }

    return answer
} 

1.146 - 2023-10-30 10:33:19 +0000 UTC

Average of Levels in Binary Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func averageOfLevels(root *TreeNode) []float64 {
    if root == nil {
        return []float64{}
    }
    queue, answer := []*TreeNode{root}, []float64{}

    for length := len(queue); length != 0; length = len(queue) {
        av := 0
        for i := 0; i < length; i++ {
            node := queue[0]
            queue = queue[1:]
            av += node.Val
            if left := node.Left; left != nil {
                queue = append(queue, left)
            }
            if right := node.Right; right != nil {
                queue = append(queue, right)
            }
        }
        answer = append(answer, float64(av) / float64(length))
    }

    return answer
}

1.147 - 2023-10-30 10:26:37 +0000 UTC

Average of Levels in Binary Tree

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func averageOfLevels(root *TreeNode) []float64 {
    if root == nil {
        return []float64{}
    }
    qCur, qNext, answer := []*TreeNode{root}, []*TreeNode{}, []float64{}

    for len(qCur) != 0 {
        av := 0
        for _, node := range qCur {
            av += node.Val
            if left := node.Left; left != nil {
                qNext = append(qNext, left)
            }
            if right := node.Right; right != nil {
                qNext = append(qNext, right)
            }
        }
        answer = append(answer, float64(av) / float64(len(qCur)))
        qCur = qCur[:0]
        qCur, qNext = qNext, qCur
    }

    return answer
}

1.148 - 2023-10-30 10:17:08 +0000 UTC

Binary Tree Right Side View

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }

    q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}

    for len(q_cur) != 0 {
        for _, node := range q_cur {
            if left := node.Left; left != nil {
                q_next = append(q_next, left)
            }
            if right := node.Right; right != nil {
                q_next = append(q_next, right)
            }
        }

        answer = append(answer, q_cur[len(q_cur) - 1].Val)
        q_cur = q_cur[:0]
        q_cur, q_next = q_next, q_cur
    }

    return answer
} 

1.149 - 2023-10-30 10:16:47 +0000 UTC

Binary Tree Right Side View

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }

    q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}

    for len(q_cur) != 0 {
        var last int
        for _, node := range q_cur {
            if left := node.Left; left != nil {
                q_next = append(q_next, left)
            }
            if right := node.Right; right != nil {
                q_next = append(q_next, right)
            }
            last = node.Val
        }

        answer = append(answer, last)
        q_cur = q_cur[:0]
        q_cur, q_next = q_next, q_cur
    }

    return answer
} 

1.150 - 2023-10-30 10:16:38 +0000 UTC

Binary Tree Right Side View

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }

    q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}

    for len(q_cur) != 0 {
        var last int
        for _, node := range q_cur {
            if left := node.Left; left != nil {
                q_next = append(q_next, left)
            }
            if right := node.Right; right != nil {
                q_next = append(q_next, right)
            }
            last = node.Val
        }

        answer = append(answer, last)
        q_cur = q_cur[:0]
        q_cur, q_next = q_next, q_cur
    }

    return answer
} 

1.151 - 2023-10-30 10:13:00 +0000 UTC

Binary Tree Right Side View

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rightSideView(root *TreeNode) []int {
    if root == nil {
        return []int{}
    }

    q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}

    for length := len(q_cur); length > 0; length = len(q_cur) {
        for _, node := range q_cur {
            if left := node.Left; left != nil {
                q_next = append(q_next, left)
            }
            if right := node.Right; right != nil {
                q_next = append(q_next, right)
            }
        }

        answer = append(answer, q_cur[length - 1].Val)
        q_cur = q_cur[:0]
        q_cur, q_next = q_next, q_cur
    }

    return answer
} 

1.152 - 2022-05-07 10:44:16 +0000 UTC

132 Pattern

Code


func find132pattern(numbers []int) bool {
	length := len(numbers)
	if length < 3 {
		// if the array doesn't have at least three numbers, it cannot have
		// '123' pattern
		return false
	}
	list, third_element := list.List{}, math.MinInt
	for index := length - 1; index >= 0; index-- {
		current := numbers[index]
		if current < third_element {
			return true
		}
		for list.Len() != 0 && list.Front().Value.(int) < current {
			third_element = list.Front().Value.(int)
			list.Remove(list.Front())
		}
		list.PushFront(current)
	}
	return false
}

1.153 - 2022-05-07 10:05:13 +0000 UTC

Backspace String Compare

Code


func backspaceCompare(string_1 string, string_2 string) bool {
	length_1, length_2 := len(string_1), len(string_2)
	list_1, list_2, length_biggest := list.List{}, list.List{}, length_1
	if length_2 > length_1 {
		length_biggest = length_2
	}
	for index := 0; index < length_biggest; index++ {
		if index < length_1 {
			backspace_action(&list_1, string_1[index])
		}
		if index < length_2 {
			backspace_action(&list_2, string_2[index])
		}
	}
	// lists are not equal, there is no need to check
	if list_1.Len() != list_2.Len() {
		return false
	}
	// checking elements after all deletions
	element_1, element_2 := list_1.Back(), list_2.Back()
	for element_1 != nil {
		if element_1.Value != element_2.Value {
			// elements are not equal -> strings are not equal
			return false
		}
		element_1, element_2 = element_1.Next(), element_2.Next()
	}
	// checked all elements, strings are equal
	return true
}

func backspace_action(list *list.List, character byte) {
	switch {
	case character == '#' && list.Len() != 0:
		// delete last character
		list.Remove(list.Front())
		fallthrough
	case character == '#' && list.Len() == 0:
		// just return if the list is empty
		return
	}
	list.PushFront(character)
}

1.154 - 2022-05-06 16:50:38 +0000 UTC

Remove Duplicates from Sorted Array

Code

func removeDuplicates(numbers []int) int {
	// ensure there are at least two numbers
	length := len(numbers)
	if length == 1 {
		return 1
	}
	index_non_duplicate := 1
	for index := 1; index < length; index++ {
		current, previous := numbers[index], numbers[index-1]
		if current == previous {
			// it is a duplicate - ignore it
			continue
		}
		// it is not a duplicate -> place it and move the index
		numbers[index_non_duplicate] = current
		index_non_duplicate++
	}
	return index_non_duplicate
}

1.155 - 2022-05-05 15:39:53 +0000 UTC

Sign of the Product of an Array

Code


func arraySign(numbers []int) int {
	negative_count := 0
	for _, number := range numbers {
		switch {
		// the number is 0 -> product of all numbers is definitely zero
		case number == 0:
			return 0
			// the number is negative -> add to count
		case number < 0:
			negative_count++
		}
	}
	// even amount of negative numbers -> result is positive
	if negative_count&1 == 0 {
		return 1
	}
	// uneven amount of negative numbers -> result is negative
	return -1
}

1.156 - 2022-05-05 15:26:39 +0000 UTC

Find Smallest Letter Greater Than Target

Code



func nextGreatestLetter(letters []byte, target byte) byte {
	length := len(letters)
	left, right := 0, length-1
	for right >= left {
		index := left + (right-left)/2
		character := letters[index]
		// the character is bigger, we found at least one result
		// smaller characters are to the left -> discard right
		if character > target {
			right = index - 1
			continue
		}
		// character is either equal or smaller -> there is no results to the
		// left -> discard left
		left = index + 1
	}
	return letters[left%length]
}

1.157 - 2022-05-05 12:37:11 +0000 UTC

Sqrt(x)

Code


func mySqrt(number int) int {
	left, right := 0, number
	for right >= left {
		current := left + (right-left)/2
		square_current := current * current
		square_next := (current + 1) * (current + 1)
		switch {
		case square_current <= number && square_next > number:
			// found the target
			return current
		case square_current > number:
			// target is to the left -> discard right
			right = current - 1
		case square_current < number:
			// target is to the right -> discard left
			left = current + 1
		}
	}
	return -1
}

1.158 - 2022-05-05 12:10:54 +0000 UTC

Reverse Words in a String III

Code

func reverseWords(_string string) string {
	index_word_start, length, result := 0, len(_string), []rune(_string)
	for index, character := range result {
		// ignore normal characters
		if character != ' ' {
			continue
		}
		// word ended -> reverse characters from the start of the word to the
		//end of it
		reverse_word(result, length, index_word_start, index)
		index_word_start = index + 1
	}
	reverse_word(result, length, index_word_start, length)
	return string(result)
}

func reverse_word(_string []rune, length int, start int, end int) {
	//fmt.Println("reversing", string(_string), start, "->", end)
	length_word := end - start
	for index := start; index < start+length_word/2; index++ {
		index_last := end - (index - start) - 1
		current, last := _string[index], _string[index_last]
		_string[index], _string[index_last] = last, current
	}
	//fmt.Println("result", string(_string), start, "->", end)
}

1.159 - 2022-05-05 10:50:33 +0000 UTC

Reverse String

Code

func reverseString(characters []byte) {
	length := len(characters)
	for index := 0; index < length/2; index++ {
		index_last := length - index -1 
		current, last := characters[index], characters[index_last]
		characters[index_last] = current
		characters[index] = last
	}
}

1.160 - 2022-05-05 10:43:47 +0000 UTC

Two Sum II - Input Array Is Sorted

Code

func twoSum(numbers []int, target int) []int {
	numbers_len := len(numbers)
	for index, number := range numbers {
		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
			if numbers[index_inner]+number == target {
				return []int{index + 1, index_inner + 1}
			}
		}
	}
	return []int{}
}

1.161 - 2022-05-05 10:39:30 +0000 UTC

Move Zeroes

Code

func moveZeroes(numbers []int) {
	index_zero := -1
	// sliding window algorithm
	for index, number := range numbers {
		// if index_zero is not set, then the first zero is index_zero
		if index_zero == -1 && number == 0 {
			index_zero = index
		}
		// there is no need to move numbers if there were no zeros before
		// there is no need to move zeros
		if index_zero == -1 || number == 0 {
			continue
		}
		// after some zeros we encounter a non-zero number
		// moving that number to the beginning of zeros
		numbers[index_zero] = number
		// current number becomes zero
		numbers[index] = 0
		// moving the index
		index_zero++
	}
}

1.162 - 2022-05-05 10:39:06 +0000 UTC

Move Zeroes

Code

func moveZeroes(nums []int)  {
    count:=0
    for i:=0; i<len(nums);i++{
        if nums[i] == 0{
            count++
        }else{
            nums[i-count]=nums[i]
        }
    }
    for count>0{
        nums[len(nums)-count] = 0
        count--
    }
    
    
}

1.163 - 2022-05-05 10:38:25 +0000 UTC

Move Zeroes

Code

func moveZeroes(nums []int)  {
    	if len(nums) < 2 {
		return
	}

	for z, p := 0, 1; p < len(nums) && z < len(nums); {
		if nums[z] == 0 && nums[p] != 0 {
			if p > z {
				nums[z], nums[p] = nums[p], nums[z]
				z++
			}
			p = z+1
		} else {
			if nums[z] != 0 {
				z++
			}
			if nums[p] == 0 {
				p++
			}
		}
	}

}

1.164 - 2022-05-05 10:32:58 +0000 UTC

Move Zeroes

Code


func moveZeroes(numbers []int) {
	index_zero := -1
	// sliding window algorithm
	for index, number := range numbers {
		// if index_zero is not set, then the first zero is index_zero
		if index_zero == -1 && number == 0 {
			index_zero = index
		}
		// there is no need to move numbers if there were no zeros before
		// there is no need to move zeros
		if index_zero == -1 || number == 0 {
			continue
		}
		// after some zeros we encounter a non-zero number
		// moving that number to the beginning of zeros
		numbers[index_zero] = number
		// current number becomes zero
		numbers[index] = 0
		// moving the index
		index_zero++
	}
}

1.165 - 2022-05-05 10:14:51 +0000 UTC

Move Zeroes

Code


func moveZeroes(numbers []int) {
	// ensure there are at least two numbers
	length := len(numbers)
	if length == 1 {
		return
	}
	result, index_result := make([]int, length), 0
	for _, number := range numbers {
		if number == 0 {
			continue
		}
		result[index_result] = number
		index_result++
	}
	copy(numbers, result)
}

1.166 - 2022-05-05 04:01:33 +0000 UTC

Implement Stack using Queues

Code


type MyStack struct{ queue *list.List }

func Constructor() MyStack           { return MyStack{&list.List{}} }
func (this *MyStack) Push(value int) { this.queue.PushFront(value) }
func (this *MyStack) Top() int       { return this.queue.Front().Value.(int) }
func (this *MyStack) Empty() bool    { return this.queue.Len() == 0 }
func (this *MyStack) Pop() int {
	return this.queue.Remove(this.queue.Front()).(int)
}

1.167 - 2022-05-04 10:13:54 +0000 UTC

Best Time to Buy and Sell Stock

Code


func maxProfit(prices []int) int {
	profit, index_buy := 0, 0
	for index, price := range prices {
		if prices[index_buy] > price {
			index_buy = index
		}
		new_profit := price - prices[index_buy]
		if new_profit > profit {
			profit = new_profit
		}
	}
	return profit
}

1.168 - 2022-05-04 09:54:11 +0000 UTC

Intersection of Two Arrays II

Code


func intersect(numbers_1 []int, numbers_2 []int) (result []int) {
	// 0 <= nums1[i], nums2[i] <= 1000
	count := make([]int, 1001)
	// counting how many times a number occured in the first array
	for _, number := range numbers_1 {
		count[number]++
	}
	for _, number := range numbers_2 {
		// the number did not occur in the first array
		// -> ignoring it
		if count[number] <= 0 {
			continue
		}
		count[number]--
		result = append(result, number)
	}
	return
}

1.169 - 2022-05-04 09:36:38 +0000 UTC

Intersection of Two Arrays II

Code


func intersect(numbers_1 []int, numbers_2 []int) []int {
	length_1, length_2 := len(numbers_1), len(numbers_2)
	length_biggest, result := length_1, make([]int, length_1+length_2)
	if length_2 > length_1 {
		length_biggest = length_2
	}
	occurences := make(map[int][]int, length_biggest)

	for index := 0; index < length_biggest; index++ {
		if index < length_1 {
			add_to_occurences(numbers_1[index], 0, occurences)
		}
		if index < length_2 {
			add_to_occurences(numbers_2[index], 1, occurences)
		}
	}
	index := 0
	for number, occurence := range occurences {
		repeat := occurence[0]
		if occurence[1] < repeat {
			repeat = occurence[1]
		}
		for ; repeat > 0; repeat-- {
			result[index] = number
			index++
		}
	}
    return result[0 : index]
}
func add_to_occurences(number int, index int, occurences map[int][]int) {
	if _, occured := occurences[number]; !occured {
		occurences[number] = make([]int, 2)
	}
	occurences[number][index]++
}

1.170 - 2022-05-04 05:33:36 +0000 UTC

Merge Sorted Array

Code


func merge(array1 []int, length1 int, array2 []int, length2 int) {
	if length2 == 0 {
		return
	}
	if length1 == 0 {
		for index, number := range array2 {
			array1[index] = number
		}
		return
	}
	index1, index2, array1Copy := 0, 0, make([]int, length1)
	copy(array1Copy, array1)
	for index := 0; index < length1+length2; index++ {
		fmt.Println(index, index1, index2, array1, array2)
		for index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
			array1[index] = array2[index2]
			index2++
			index++
		}
		if index1 >= length1 {
			continue
		}
		array1[index] = array1Copy[index1]
		index1++
	}
}

1.171 - 2022-05-04 05:32:16 +0000 UTC

Two Sum

Code


func twoSum(numbers []int, target int) []int {
	numbers_len := len(numbers)
	for index, number := range numbers {
		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
			if numbers[index_inner]+number == target {
				return []int{index, index_inner}
			}
		}
	}
	return []int{}
}

1.172 - 2022-05-04 05:30:20 +0000 UTC

Find the Distance Value Between Two Arrays

Code


func findTheDistanceValue(array_1 []int, array_2 []int, target int) int {
	// sorting it to use binary search
	sort.Ints(array_2)
	length_2, count := len(array_2), 0
	for _, current_1 := range array_1 {
		left, right, add_to_count := 0, length_2-1, true
		for right >= left {
			index := left + (right-left)/2
			current_2 := array_2[index]
			if abs(current_1, current_2) <= target {
				// current_1 is inside |arr1[i]-arr2[j]| <= d
				// -> ignore it
				add_to_count = false
				break
			}
			switch {
			case current_2 > current_1:
				// current_2 is bigger than current_1
				// -> all numbers to the right are bigger
				// -> discard right, add to count
				right = index - 1
			case current_2 < current_1:
				// current_2 is smaller than current_1
				// -> all numbers to the left are smaller
				// -> discard left, add to count
				left = index + 1
			}
		}
		if add_to_count {
			count++
		}
	}
	return count
}

func abs(number_1 int, number_2 int) int {
	difference := number_1 - number_2
	if difference < 0 {
		return difference * -1
	}
	return difference
}

1.173 - 2022-05-04 04:34:24 +0000 UTC

Valid Perfect Square

Code


func isPerfectSquare(number int) bool {
	left, right := 1, number
	for right >= left {
		current := left + (right-left)/2
		square := current * current
		switch {
		case square == number:
			// found the target
			return true
		case square > number:
			// square is bigger -> root is to the left -> discard right
			right = current - 1
		case square < number:
			// square is smaller -> root is to the right -> discard left
			left = current + 1
		}
	}
	return false
}

1.174 - 2022-05-04 04:03:31 +0000 UTC

Find Nearest Point That Has the Same X or Y Coordinate

Code

func nearestValidPoint(x int, y int, points [][]int) int {
	point_target, smallest_distance, smallest_index := []int{x, y}, math.MaxInt, -1
	for index, point := range points {
		// ignore the point if it is not valid
		if !valid(point_target, point) {
			continue
		}
		distance := distance(point_target, point)
		// ignore the point if its Manhattan distance is bigger
		if distance >= smallest_distance {
			continue
		}
		// the distance is smaller, update the index and the distance
		smallest_index, smallest_distance = index, distance
	}
	// there are no valid points
	if smallest_index == -1 {
		return -1
	}
	return smallest_index
}

func valid(point_target []int, point []int) bool {
	switch {
	case point_target[0] == point[0]:
		fallthrough
	case point_target[1] == point[1]:
		return true
	default:
		return false
	}
}

func distance(point_target []int, point []int) int {
	return abs(point_target[0]-point[0]) + abs(point_target[1]-point[1])
}

func abs(number int) int {
	if number < 0 {
		return number * -1
	}
	return number
}

1.175 - 2022-05-04 03:39:29 +0000 UTC

Largest Perimeter Triangle

Code


func largestPerimeter(numbers []int) int {
	sort.Ints(numbers)
	for index := len(numbers) - 1; index > 1; index-- {
		current, sum_previous := numbers[index], numbers[index-1]+numbers[index-2]
		if current >= sum_previous {
			continue
		}
		return current + sum_previous
	}
	return 0
}

1.176 - 2022-05-04 03:26:24 +0000 UTC

Max Number of K-Sum Pairs

Code


func maxOperations(numbers []int, sum int) int {
	count, previous := 0, make(map[int]int, len(numbers))
	for _, current := range numbers {
		target := sum - current
		target_unmatched, target_occured := previous[target]
		// if the current number has not occured before, then it is not in the map
		// -> it needs to be initialized
		if _, current_occured := previous[current]; !current_occured {
			previous[current] = 0
		}
		// number of duplicates of the current number has increased
		previous[current]++
		switch {
		case target_occured && target_unmatched == 0:
			// the target has occured before but there are no unmatched duplicates
			fallthrough
		case !target_occured:
			// in order to get the sum we need the target, but it has not appeared yet
			continue
		case target_occured && target_unmatched > 0:
			// the target has appeared before and there are some unmached duplicates left
			// -> removing the current number and the target from possible matches
			previous[current]--
			previous[target]--
			count++
		}
	}
	return count
}

1.177 - 2022-05-04 02:57:55 +0000 UTC

Subtract the Product and Sum of Digits of an Integer

Code

func subtractProductAndSum(number int) int {
	fist_digit := number % 10
	factorial, sum := fist_digit, fist_digit
	number /= 10
	for number > 0 {
		digit := number % 10
		factorial *= digit
		sum += digit
		number /= 10
	}
	return factorial - sum
}

1.178 - 2022-05-04 02:49:11 +0000 UTC

Number of 1 Bits

Code


func hammingWeight(number uint32) (result int) {
	for number > 0 {
		if number&1 != 0 {
			result++
		}
		number >>= 1
	}
	return
}

1.179 - 2022-05-03 15:34:04 +0000 UTC

Peak Index in a Mountain Array

Code


func peakIndexInMountainArray(array []int) int {
	left, right := 0, len(array)-1
	for right > left {
		// overflow protection
		index := left + (right-left)/2
		// next element is bigger -> top is to the right -> discard left
		if array[index+1] > array[index] {
			left = index + 1
			continue
		}
		// next element is equal or smaller -> discard right
		// 'index' could be the answer, so it should not be discarded
		right = index
	}
	return right
}

1.180 - 2022-05-03 14:44:29 +0000 UTC

Search Insert Position

Code

func searchInsert(numbers []int, target int) int {
	// checking edge cases
	length := len(numbers)
	if numbers[0] == target {
		return 0
	} else if numbers[length-1] == target {
		return length - 1
	}
	left, right, index, was_bigger := 0, length-1, 0, false
	for right >= left {
		// overflow protection
		index = left + (right-left)/2
		number := numbers[index]
		//fmt.Println("index", index, "left", left, "right", right)
		switch {
		case number == target:
			// found the target
			return index
		case number > target:
			// the number is bigger -> the target is to the left -> discard right
			right = index - 1
			was_bigger = true
		case number < target:
			// the number is smaller -> the target is to the right -> discard left
			left = index + 1
			was_bigger = false
		}
	}
	// the target is not in the array

	// the last number was bigger -> target should be to the left
	if was_bigger {
		return index
	}
	// the last number was smaller -> target should be to the right
	return index + 1
}

1.181 - 2022-05-03 14:39:58 +0000 UTC

Rotate Array

Code


func rotate(numbers []int, steps int) {
	length := len(numbers)
	// removing unnecessary steps
	if steps >= length {
		steps %= length
	}
	// checking edge cases
	if length == 1 || steps == 0 {
		return
	}
	results := make([]int, length)
	for index, number := range numbers {
		results[(index+steps)%length] = number
	}
	copy(numbers, results)
}

1.182 - 2022-05-03 12:28:52 +0000 UTC

Rotate Array

Code


func rotate(numbers []int, steps int) {
	length := len(numbers)
	// removing unnecessary steps
	if steps >= length {
		steps %= length
	}
	// checking edge cases
	if length == 1 || steps == 0 {
		return
	}
	remainder, rotation_start := make([]int, steps), length-steps
	// copy everything that needs to be shifted to another array
	copy(remainder, numbers[rotation_start:])
	// move everything to the right
	copy(numbers[steps:], numbers[0:rotation_start])
	// move shifted elements to the beginning
	copy(numbers[0:steps], remainder)
}

1.183 - 2022-05-03 12:08:53 +0000 UTC

Squares of a Sorted Array

Code

func sortedSquares(numbers []int) []int {
	length := len(numbers)
	if length == 0 || length == 1 {
		return square(numbers, false)
	}
	negativesIndex := -1
	for index, number := range numbers {
		if number >= 0 {
			negativesIndex = index
			break
		}
	}
	if negativesIndex == 0 || negativesIndex == -1 {
		return square(numbers, negativesIndex == -1)
	}
//	fmt.Println("negativesIndex", negativesIndex)
	result, resultIndex, negativesIndex := make([]int, length), 0, negativesIndex-1
	for positivesIndex := negativesIndex + 1; resultIndex < length; positivesIndex++ {
		positiveOverflow := positivesIndex >= length
		for {
			if negativesIndex < 0 || resultIndex >= length {
				break
			}
			if !positiveOverflow && numbers[negativesIndex]*-1 > numbers[positivesIndex] {
				break
			}
			result[resultIndex] = numbers[negativesIndex]
			resultIndex++
//			fmt.Println("negative", negativesIndex, resultIndex, numbers[negativesIndex], result, numbers)
			negativesIndex--
		}
		if resultIndex < length && !positiveOverflow {
//			fmt.Println("positivesIndex", positivesIndex, resultIndex, numbers[positivesIndex], result, numbers)
			result[resultIndex] = numbers[positivesIndex]
			resultIndex++
		}
	}
	return square(result, false)
}

func square(array []int, reverse bool) []int {
	if reverse {
		length := len(array)
		reversed := make([]int, length)
		for index := length - 1; index >= 0; index-- {
			reversed[length-index-1] = array[index] * array[index]
		}
		return reversed
	} else {
		for index, number := range array {
			array[index] = number * number
		}
		return array
	}
}

1.184 - 2022-05-03 12:05:02 +0000 UTC

Squares of a Sorted Array

Code


func sortedSquares(numbers []int) []int {
	length := len(numbers)
	switch length {
	case 0:
		return numbers
	case 1:
		return []int{numbers[0] * numbers[0]}
	}
	index_left, index_right := 0, length-1
	results := make([]int, length)
	for index := index_right; index_left <= index_right; index-- {
		left_square := numbers[index_left] * numbers[index_left]
		right_square := numbers[index_right] * numbers[index_right]
		if right_square > left_square {
			results[index] = right_square
			index_right--
			continue
		}
		results[index] = left_square
		index_left++
	}
	return results
}

1.185 - 2022-05-03 10:17:41 +0000 UTC

Shortest Unsorted Continuous Subarray

Code


func findUnsortedSubarray(numbers []int) int {
	length := len(numbers)
	// checking edge cases
	if length == 1 {
		return 0
	}
	result := make([]int, length)
	// initializing to MaxInt because zeros will impact future sorting
	for index := range result {
		result[index] = math.MaxInt
	}
	index_sort_start, index_sort_end := length, length
	result[0] = numbers[0]
	for index := 1; index < length; index++ {
//		fmt.Println(result, index_sort_start, "->", index_sort_end)
		// current is not sorted -> from numbers
		// previous is sorted -> from result
		current, previous := numbers[index], result[index-1]
		// just push the current number in the result array because if it is
		// bigger
		if current >= previous {
			result[index] = current
			continue
		}
		// current number is not sorted -> moving the end index
		index_sort_end = index + 1
		// current < previous -> find the number bigger than the current
		//
		// the current number is smaller than the starting number of the unsorted subarray
		// (or the starting index is not set)
		// -> start index is invalid, finding new start index in numbers
		if index_sort_start == length || current < result[index_sort_start] {
			// insert the number in the correct place and move index_sort_start
			// to the correct place
			if index_sort_start == length {
				// index_sort_start is not set -> setting to the last sorted number
				index_sort_start = index - 1
			}
			index_sort_start = insert_smaller(result, current, index_sort_start, 0)
			continue
		}
		// the current number is bigger than the starting number of the unsorted
		// subarray, so it should be placed inside of it
		insert_smaller(result, current, index, index_sort_start)
		// set start index (if not already set)
		if index < index_sort_start {
			index_sort_start = index - 1
		}
	}
//	fmt.Println(result, index_sort_start, "->", index_sort_end)
	// return length of the sorted subarray
	return index_sort_end - index_sort_start
}

func insert_smaller(numbers []int, target int, index_start int, index_end int) int {
	index_result := index_end
	for index := index_start; index >= index_end; index-- {
		if target >= numbers[index] {
			// target is bigger -> it should be placed after this index
			index_result = index + 1
			break
		}
	}
//	fmt.Println("index for", target, "-", index_result)
	// target should be placed after index_result, so move everything after
	// it to the right and insert the current number
	// if index_result is the last item, then just push it
	copy(numbers[index_result+1:], numbers[index_result:])
	numbers[index_result] = target
	return index_result
}

1.186 - 2022-05-03 10:17:21 +0000 UTC

Shortest Unsorted Continuous Subarray

Code


func findUnsortedSubarray(numbers []int) int {
	length := len(numbers)
	// checking edge cases
	if length == 1 {
		return 0
	}
	result := make([]int, length)
	// initializing to MaxInt because zeros will impact future sorting
	for index := range result {
		result[index] = math.MaxInt
	}
	index_sort_start, index_sort_end := length, length
	result[0] = numbers[0]
	for index := 1; index < length; index++ {
//		fmt.Println(result, index_sort_start, "->", index_sort_end)
		// current is not sorted -> from numbers
		// previous is sorted -> from result
		current, previous := numbers[index], result[index-1]
		// just push the current number in the result array because if it is
		// bigger
		if current >= previous {
			result[index] = current
			continue
		}
		// current number is not sorted -> moving the end index
		index_sort_end = index + 1
		// current < previous -> find the number bigger than the current
		//
		// the current number is smaller than the starting number of the unsorted subarray
		// (or the starting index is not set)
		// -> start index is invalid, finding new start index in numbers
		if index_sort_start == length || current < result[index_sort_start] {
			// insert the number in the correct place and move index_sort_start
			// to the correct place
			if index_sort_start == length {
				// index_sort_start is not set -> setting to the last sorted number
				index_sort_start = index - 1
			}
			index_sort_start = insert_smaller(result, current, index_sort_start, 0)
			continue
		}
		// the current number is bigger than the starting number of the unsorted
		// subarray, so it should be placed inside of it
		insert_smaller(result, current, index, index_sort_start)
		// set start index (if not already set)
		if index < index_sort_start {
			index_sort_start = index - 1
		}
	}
//	fmt.Println(result, index_sort_start, "->", index_sort_end)
	// return length of the sorted subarray
	return index_sort_end - index_sort_start
}

func insert_smaller(numbers []int, target int, index_start int, index_end int) int {
	index_result := index_end
	for index := index_start; index >= index_end; index-- {
		if target >= numbers[index] {
			// target is bigger -> it should be placed after this index
			index_result = index + 1
			break
		}
	}
//	fmt.Println("index for", target, "-", index_result)
	// target should be placed after index_result, so move everything after
	// it to the right and insert the current number
	// if index_result is the last item, then just push it
	copy(numbers[index_result+1:], numbers[index_result:])
	numbers[index_result] = target
	return index_result
}

1.187 - 2022-05-02 16:07:40 +0000 UTC

Sort Array By Parity

Code


func sortArrayByParity(numbers []int) []int {
	length := len(numbers)
	if length == 1 {
		return numbers
	}
	results, index_even, index_odd := make([]int, length), 0, length-1
	for _, number := range numbers {
		if (number & 1) == 0 {
			// number is even -> place it from the beginning
			results[index_even] = number
			index_even++
		} else {
			// number is odd -> place it from the end
			results[index_odd] = number
			index_odd--
		}
	}
	return results
}

1.188 - 2022-05-02 15:49:07 +0000 UTC

Search Insert Position

Code

func searchInsert(numbers []int, target int) int {
	// checking edge cases
	length := len(numbers)
	if numbers[0] == target {
		return 0
	} else if numbers[length-1] == target {
		return length - 1
	}
	left, right, index, was_bigger := 0, length-1, 0, false
	for right >= left {
		// overflow protection
		index = left + (right-left)/2
		number := numbers[index]
		//fmt.Println("index", index, "left", left, "right", right)
		switch {
		case number == target:
			// found the target
			return index
		case number > target:
			// the number is bigger -> the target is to the left -> discard right
			right = index - 1
			was_bigger = true
		case number < target:
			// the number is smaller -> the target is to the right -> discard left
			left = index + 1
			was_bigger = false
		}
	}
	// the target is not in the array

	// the last number was bigger -> target should be to the left
	if was_bigger {
		return index
	}
	// the last number was smaller -> target should be to the right
	return index + 1
}

1.189 - 2022-05-02 15:02:36 +0000 UTC

First Bad Version

Code


func firstBadVersion(n int) int {
	// checking edge cases
	if isBadVersion(1) {
		return 1
	}
	left, right, bad_version := 1, n, math.MaxInt
	for right >= left {
		// overflow protection
		version := left + (right-left)/2
		switch isBadVersion(version) {
		case false:
			// it is good -> versions to the left are good -> discard left
			left = version + 1
		case true:
			// it is bad -> the first bad version is either this one or to the left
			// discard right
			bad_version = version
			right = version - 1
		}
	}
	// the search space is empty
	return bad_version
}

1.190 - 2022-05-02 14:51:33 +0000 UTC

Binary Search

Code

/* https://leetcode.com/problems/binary-search/

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.



Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1



Constraints:

    1 <= nums.length <= 104
    -104 < nums[i], target < 104
    All the integers in nums are unique.
    nums is sorted in ascending order.

*/
package main

func search(numbers []int, target int) int {
	length := len(numbers)
	switch {
	case numbers[0] > target:
		// smallet number > target = there is no target in the array
		fallthrough
	case numbers[length-1] < target:
		// biggest number < target = there is no target in the array
		return -1
	case numbers[length-1] == target:
		// checking just in case, can save time
		return length - 1
	case numbers[0] == target:
		// checking just in case, can save time
		return 0
	}

	left, right := 0, length-1
	for right >= left {
		// overflow protection
		index := left + (right-left)/2
		number := numbers[index]
		switch {
		case number == target:
			// found the target
			return index
		case number > target:
			// array is in the ascending order, the number is bigger
			// -> the target is to the left -> discard right
			right = index - 1
		case number < target:
			// array is in the ascending order, the number is smaller
			// -> the target is to the right -> discard left
			left = index + 1
		}
	}
	// search space is empty, there is no target
	return -1
}

1.191 - 2022-05-02 14:49:22 +0000 UTC

Guess Number Higher or Lower

Code


func guessNumber(n int) int {
	// checking edge cases
	if guess(1) == 0 {
		return 1
	} else if guess(n) == 0 {
		return n
	}
	left, right := 1, n
	for right >= left {
		// overflow protection
		number := left + (right-left)/2
		switch guess(number) {
		case 0:
			// found the target
			return number
		case -1:
			// the number is bigger -> the target is to the left -> discard right
			right = number - 1
		case 1:
			// the number is smaller -> the target is to the right -> discard left
			left = number + 1
		}
	}
	// ide shows an error, this return is unreachable in this issue
	return 0
}

1.192 - 2022-05-02 14:34:04 +0000 UTC

Binary Search

Code

/* https://leetcode.com/problems/binary-search/

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.



Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1



Constraints:

    1 <= nums.length <= 104
    -104 < nums[i], target < 104
    All the integers in nums are unique.
    nums is sorted in ascending order.

*/
package main

func search(numbers []int, target int) int {
	length := len(numbers)
	switch {
	case numbers[0] > target:
		// smallet number > target = there is no target in the array
		fallthrough
	case numbers[length-1] < target:
		// biggest number < target = there is no target in the array
		return -1
	case numbers[length-1] == target:
		// checking just in case, can save time
		return length - 1
	case numbers[0] == target:
		// checking just in case, can save time
		return 0
	}

	left, right := 0, length-1
	for right >= left {
		// overflow protection
		index := left + (right-left)/2
		number := numbers[index]
		switch {
		case number == target:
			// found the target
			return index
		case number > target:
			// array is in the ascending order, the number is bigger
			// -> the target is to the left -> discard right
			right = index - 1
		case number < target:
			// array is in the ascending order, the number is smaller
			// -> the target is to the right -> discard left
			left = index + 1
		}
	}
	// search space is empty, there is no target
	return -1
}

1.193 - 2022-05-02 13:35:35 +0000 UTC

Average Salary Excluding the Minimum and Maximum Salary

Code


func average(salary []int) float64 {
	length := len(salary)
	highest, lowest := math.MinInt, math.MaxInt
	result := 0
	for _, number := range salary {
		result += number
		if number > highest {
			highest = number
		}
		if number < lowest {
			lowest = number
		}
	}
	return float64(result-highest-lowest) / float64(length-2)
}

1.194 - 2022-05-02 13:28:49 +0000 UTC

Count Odd Numbers in an Interval Range

Code


func countOdds(low int, high int) int {
	low_even, high_even, half := (low&1) == 0, (high&1) == 0, (high-low)/2
	if low_even && high_even  {
		return half
	}
	return half + 1
}

1.195 - 2022-05-02 11:58:45 +0000 UTC

Maximum Subarray

Code


func maxSubArray(numbers []int) int {
	length := len(numbers)
	switch length {
	case 0:
		return 0
	case 1:
		return numbers[0]
	}
	maxCurrent, maxOverall := 0, math.MinInt
	for _, number := range numbers {
		maxCurrent += number
		if maxCurrent > maxOverall {
			maxOverall = maxCurrent
		}
		if maxCurrent < 0 {
			maxCurrent = 0
		}
	}
	return maxOverall
}

1.196 - 2022-05-02 04:24:29 +0000 UTC

Contains Duplicate

Code


func containsDuplicate(numbers []int) bool {
	if len(numbers) == 0 || len(numbers) == 1 {
		return false
	}
	occured := make(map[int]bool)
	for _, number := range numbers {
		_, isDuplicate := occured[number]
		if isDuplicate {
			return true
		}
		occured[number] = true
	}
	return false
}

1.197 - 2022-05-01 13:23:58 +0000 UTC

Add to Array-Form of Integer

Code

func addToArrayForm(number1 []int, add int) []int {
	if add == 0 {
		return number1
	}
	if len(number1) == 0 {
		return convert(add)
	}
	number2 := convert(add)
	length1, length2, carry := len(number1), len(number2), 0
	hightest := length1
	if length2 > length1 {
		hightest = length2
	}
	result := make([]int, hightest)
	index1, index2, indexResult := length1-1, 0, hightest-1
	for {
		index1Valid, index2Valid := index1 >= 0, index2 < length2
		if !index1Valid && !index2Valid && carry==0 {
			break
		}
		digit1, digit2 := 0, 0
		if index1Valid {
			digit1 = number1[index1]
			index1--
		}
		if index2Valid {
			digit2 = number2[index2]
			index2++
		}
		digitResult := digit1 + digit2 + carry
		if digitResult > 9 {
			carry = 1
			digitResult -= 10
		} else {
			carry = 0
		}
		if indexResult == -1 {
			result = append(result, 0)
			copy(result[1:], result[0:hightest])
            indexResult=0
		}
		result[indexResult] = digitResult
		indexResult--
	}
	return result
}

func convert(number int) (result []int) {
	for {
		if number == 0 {
			return
		}
		result = append(result, number%10)
		number /= 10
	}
}

1.198 - 2022-05-01 12:41:08 +0000 UTC

Squares of a Sorted Array

Code


func sortedSquares(numbers []int) []int {
	length := len(numbers)
	if length == 0 || length == 1 {
		return square(numbers, false)
	}
	negativesIndex := -1
	for index, number := range numbers {
		if number >= 0 {
			negativesIndex = index
			break
		}
	}
	if negativesIndex == 0 || negativesIndex == -1 {
		return square(numbers, negativesIndex == -1)
	}
	//fmt.Println("negativesIndex", negativesIndex)
	result, resultIndex, negativesIndex := make([]int, length), 0, negativesIndex-1
	for positivesIndex := negativesIndex + 1; resultIndex < length; positivesIndex++ {
		positiveOverflow := positivesIndex >= length
		for {
			if negativesIndex < 0 || resultIndex >= length {
				break
			}
			if !positiveOverflow && numbers[negativesIndex]*-1 > numbers[positivesIndex] {
				break
			}
			
			result[resultIndex] = numbers[negativesIndex]
			resultIndex++
			//fmt.Println("negative", negativesIndex, resultIndex, numbers[negativesIndex], result, numbers)
            negativesIndex--
		}
		if resultIndex < length && !positiveOverflow {
	//		fmt.Println("positivesIndex", positivesIndex, resultIndex, numbers[positivesIndex], result, numbers)
			result[resultIndex] = numbers[positivesIndex]
			resultIndex++
		}
	}
	return square(result, false)
}

func square(array []int, reverse bool) []int {
	if reverse {
		length := len(array)
		reversed := make([]int, length)
		for index := length - 1; index >= 0; index-- {
			reversed[length-index-1] = array[index] * array[index]
		}
		return reversed
	} else {
		for index, number := range array {
			array[index] = number * number
		}
		return array
	}
}

1.199 - 2022-05-01 10:28:32 +0000 UTC

Merge Sorted Array

Code


func merge(array1 []int, length1 int, array2 []int, length2 int) {
	if length2 == 0 {
		return
	} 
    if length1 == 0 {
		for index, number := range array2 {
			array1[index] = number
		}
		return
	}
	index1, index2, array1Copy := 0, 0, make([]int, length1)
	copy(array1Copy, array1)
	for index := 0; index < length1+length2; index++ {
		//fmt.Println(index, index1, index2, array1, array2)
		for index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
			array1[index] = array2[index2]
			index2++
			index++
		}
		if index1 >= length1 {
			continue
		}
		array1[index] = array1Copy[index1]
		index1++
	}
}

1.200 - 2022-05-01 10:12:45 +0000 UTC

Merge Sorted Array

Code


func merge(array1 []int, length1 int, array2 []int, length2 int) {
	index1, index2, array1Copy := 0, 0, make([]int, length1)
	copy(array1Copy, array1)
	for index := 0; index < length1+length2; index++ {
		fmt.Println(index, index1, index2, array1, array2)
		if index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
			array1[index] = array2[index2]
			index2++
			continue
		}
		array1[index] = array1Copy[index1]
		index1++

	}
}

1.201 - 2022-05-01 06:06:49 +0000 UTC

Merge Two Sorted Lists

Code

func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	// ensure both lists are valid
	switch {
	case list1 == nil && list2 == nil:
		return nil
	case list1 == nil && list2 != nil:
		return list2
	case list1 != nil && list2 == nil:
		return list1
	}
	var root *ListNode
	if list1.Val < list2.Val {
		root = &ListNode{list1.Val, nil}
		list1 = list1.Next
	} else {
		root = &ListNode{list2.Val, nil}
		list2 = list2.Next
	}
	current := &root
	for {
		switch {
		case list1 == nil && list2 == nil:
			return root
		case list1 != nil && list2 != nil && list1.Val <= list2.Val:
			fallthrough
		case list1 != nil && list2 == nil:
			fmt.Println("1", list1.Val)
			updateResult(&current, &list1)
		case list1 != nil && list2 != nil && list1.Val > list2.Val:
			fallthrough
		case list1 == nil && list2 != nil:
			fmt.Println("2", list2.Val)
			updateResult(&current, &list2)
		}
	}
}
func updateResult(current ***ListNode, node **ListNode) {
	// modify the current result node
	(**current).Next = &ListNode{(*node).Val, nil}
	// move the current pointer
	*current = &(**current).Next
	// there is no next node -> nill it
	// there is next -> move it
	if (*node).Next == nil {
		*node = nil
	} else {
		*node = (*node).Next
	}
}

1.202 - 2022-04-30 19:06:12 +0000 UTC

Valid Parentheses

Code


func isValid(inputString string) bool {
	if len(inputString) == 0 || (len(inputString)&1) != 0 {
		return false
	}
	occurences := []rune{}
	ends := map[rune]rune{')': '(', '}': '{', ']': '['}
	for _, character := range inputString {
		length := len(occurences)
		last_valid, is_end := ends[character]
		if (is_end && length == 0) || (is_end && occurences[length-1] != last_valid) {
			return false
		}
		if is_end {
			occurences = occurences[0 : length-1]
		} else {
			occurences = append(occurences, character)
		}
	}
	if len(occurences) > 0 {
		return false
	}
	return true
}

1.203 - 2022-04-30 17:27:04 +0000 UTC

Find Palindrome With Fixed Length

Code

func kthPalindrome(queries []int, intLength int) (answer []int64) {
	for _, query := range queries {
		answer = append(answer, getPalindrom(query, intLength))
	}
	return
}

func getPalindrom(query int, length int) (result int64) {
	is_even := (length & 1) == 0
	power := length / 2
	if is_even {
		power -= 1
	}
	palindrome := int64(math.Pow10(power)) + int64(query) - 1
	result = palindrome
	if !is_even {
		palindrome /= 10
	}
	for palindrome > 0 {
		result = result*10 + palindrome%10
		palindrome /= 10
	}
	if len(fmt.Sprint(result)) != length {
		return -1
	}
	return
}

1.204 - 2022-04-30 06:12:31 +0000 UTC

Palindrome Number

Code


func isPalindrome(number int) (result bool) {
	if number < 0 {
		return false
	} else if number/10 == 0 {
		return true
	}
	current := number
	digits := []int{}
	for {
		if current == 0 {
			break
		}
		digit := current % 10
		current /= 10
		digits = append(digits, digit)
	}
	digits_length := len(digits)
	skip := -1
	if digits_length%2 != 0 {
		skip = digits_length / 2
	}
	for index, digit := range digits {
		if index != skip && digit != digits[digits_length-index-1] {
			return false
		}
	}
	return true
}

1.205 - 2022-04-30 05:49:48 +0000 UTC

Two Sum IV - Input is a BST

Code

import "sort"
func construct(root *TreeNode, results map[int]int) {
	if root == nil {
		return
	}
	if results[root.Val] < 2 {
		results[root.Val] += 1
	}
	construct(root.Left, results)
	construct(root.Right, results)
}

func sorted(input_map map[int]int) (results []int) {
	for key := range input_map {
		results = append(results, key)
	}
	return
}

func findTarget(root *TreeNode, target int) bool {
	if root == nil {
		return false
	}
	results := map[int]int{}
	construct(root, results)
	if target%2 == 0 && results[target/2] == 2 {
		return true
	}
	results_sorted := sorted(results)
	results_sorted_len := len(results_sorted)
	sort.Ints(results_sorted)
	for index, number := range results_sorted {
		for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
			if number+results_sorted[index_inner] == target {
				return true
			}
		}
	}
	return false
}

1.206 - 2022-04-30 05:49:00 +0000 UTC

Two Sum IV - Input is a BST

Code

import "sort"

func construct(root *TreeNode, results map[int]bool, doubles map[int]bool) {
	if root == nil {
		return
	}
	_, exists := results[root.Val]
	if !exists {
		results[root.Val] = true
	} else if _, double := doubles[root.Val]; exists && double {
		doubles[root.Val] = true
	}
	construct(root.Left, results, doubles)
	construct(root.Right, results, doubles)
}

func sorted(input_map map[int]bool) (results []int) {
	for key := range input_map {
		results = append(results, key)
	}
	return
}

func findTarget(root *TreeNode, target int) bool {
	if root == nil {
		return false
	}
	results := map[int]bool{}
	doubles := map[int]bool{}
	construct(root, results, doubles)
	if _, double_exists := doubles[target/2]; target%2 == 0 && double_exists {
		return true
	}
	results_sorted := sorted(results)
	results_sorted_len := len(results_sorted)
	sort.Ints(results_sorted)
	for index, number := range results_sorted {
		for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
			if number+results_sorted[index_inner] == target {
				return true
			}
		}
	}
	return false
}

1.207 - 2022-04-30 05:30:40 +0000 UTC

Two Sum IV - Input is a BST

Code

import "sort"

func construct(root *TreeNode, results map[int]int) {
	if root == nil {
		return
	}
	if results[root.Val] < 2 {
		results[root.Val] += 1
	}
	construct(root.Left, results)
	construct(root.Right, results)
}

func sorted(input_map map[int]int) (results []int) {
	for key := range input_map {
		results = append(results, key)
	}
	return
}

func findTarget(root *TreeNode, target int) bool {
	if root == nil {
		return false
	}
	results := map[int]int{}
	construct(root, results)
	if target%2 == 0 && results[target/2] == 2 {
		return true
	}
	results_sorted := sorted(results)
	results_sorted_len := len(results_sorted)
	sort.Ints(results_sorted)
	for index, number := range results_sorted {
		for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
			if number+results_sorted[index_inner] == target {
				return true
			}
		}
	}
	return false
}

1.208 - 2022-04-30 04:52:06 +0000 UTC

Two Sum IV - Input is a BST

Code


func construct(root *TreeNode, results map[int]int) {
	if root == nil {
		return
	}
	if results[root.Val] < 2 {
		results[root.Val] += 1
	}
	construct(root.Left, results)
	construct(root.Right, results)
}

func findTarget(root *TreeNode, target int) bool {
	results := map[int]int{}
	construct(root, results)
	for number, count := range results {
		if count == 2 && number*2 == target {
			return true
		}
		for number_inner := range results {
			if number_inner <= number {
				continue
			}
			if number+number_inner == target {
				return true
			}
		}
	}
	return false
}

1.209 - 2022-04-30 03:41:23 +0000 UTC

Two Sum II - Input Array Is Sorted

Code

func twoSum(numbers []int, target int) []int {
	numbers_len := len(numbers)
	for index, number := range numbers {
		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
			if numbers[index_inner]+number == target {
				return []int{index + 1, index_inner + 1}
			}
		}
	}
	return []int{}
}

1.210 - 2022-04-30 03:29:16 +0000 UTC

Two Sum

Code

func twoSum(numbers []int, target int) []int {
	numbers_len := len(numbers)
	for index, number := range numbers {
		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
			if numbers[index_inner]+number == target {
				return []int{index, index_inner}
			}
		}
	}
	return []int{}
}

1.211 - 2022-04-30 02:36:04 +0000 UTC

Add Two Numbers II

Code

func reverse(list *ListNode) *ListNode {
	if list == nil || list.Next == nil {
		return list
	}
	result := &ListNode{list.Val, nil}
	current := list.Next
	for {
		if current == nil {
			return result
		}
		result = &ListNode{current.Val, result}
        current = current.Next
	}
}

func addTwoNumbers(list_1 *ListNode, list_2 *ListNode) *ListNode {
	current_1, current_2, result := reverse(list_1), reverse(list_2), &ListNode{}
	var carry int
	result_current := result
	for {
		var value_1, value_2 int
		if current_1 != nil {
			value_1 = current_1.Val
			current_1 = current_1.Next
		}
		if current_2 != nil {
			value_2 = current_2.Val
			current_2 = current_2.Next
		}
		sum := value_1 + value_2 + carry
		if sum > 9 {
			sum -= 10
			carry = 1
		} else {
			carry = 0
		}
		result_current.Val = sum
		if current_1 == nil && current_2 == nil && carry == 0 {
			result_current.Next = nil
			return reverse(result)
		} else if current_1 == nil && current_2 == nil && carry != 0 {
			current_1 = &ListNode{}
		}
		result_current.Next = &ListNode{}
		result_current = result_current.Next
	}
}

1.212 - 2022-04-29 19:10:38 +0000 UTC

Add Two Numbers

Code


func addTwoNumbers(list_1 *ListNode, list_2 *ListNode) *ListNode {
	current_1, current_2, result := list_1, list_2, &ListNode{}
	var carry int
	result_current := result
	for {
		var value_1, value_2 int
		if current_1 != nil {
			value_1 = current_1.Val
			current_1 = current_1.Next
		}
		if current_2 != nil {
			value_2 = current_2.Val
			current_2 = current_2.Next
		}
		sum := value_1 + value_2 + carry
		if sum > 9 {
			sum -= 10
			carry = 1
		} else {
			carry = 0
		}
		result_current.Val = sum
		if current_1 == nil && current_2 == nil && carry == 0 {
			result_current.Next = nil
			return result
		} else if current_1 == nil && current_2 == nil && carry != 0 {
			current_1 = &ListNode{}
		}
		result_current.Next = &ListNode{}
		result_current = result_current.Next
	}
}

1.213 - 2022-04-29 16:52:46 +0000 UTC

Longest Common Prefix

Code

func longestCommonPrefix(strings []string) string {
	switch len(strings) {
	case 0:
		return ""
	case 1:
		return strings[0]
	}
	result := strings[0]
for index := 1; index < len(strings); index++ {
		current := strings[index]
		previous := strings[index-1]
		current_max := len(current)
		result_max := len(result)
		var slice_max int
		if result_max > current_max {
			slice_max = current_max
			result = result[0:slice_max]
		} else {
			slice_max = result_max
		}
		for ; slice_max >= 0; slice_max-- {
			current_slice := current[0:slice_max]
			if current_slice == previous[0:slice_max] {
				result = current_slice
				break
			}
			if slice_max == 0 {
				return ""
			}
		}
	}	
    return result
}

1.214 - 2022-04-29 15:51:04 +0000 UTC

Longest Common Prefix

Code


func substrings(input string) map[string]bool {
	results := make(map[string]bool)
	for index := range input {
		results[input[0:index+1]] = true
	}
	return results
}

func string_in_maps(
	source map[string]bool,
	target map[string]bool,
	results map[string]bool) {
	for string := range source {
		is_valid, exists_in_results := results[string]
		_, exists_in_target := target[string]
		switch {
		case !exists_in_target:
			fallthrough
		case exists_in_target && (is_valid || !exists_in_results):
			results[string] = exists_in_target
		}
	}
}

func longestCommonPrefix(strings []string) (result string) {
	results := make(map[string]bool)
	var previous map[string]bool
	for index, string := range strings {
		current := substrings(string)
		if index == 0 {
			previous = current
		}
		string_in_maps(previous, current, results)
		string_in_maps(current, previous, results)
		previous = current
	}
	for string, valid := range results {
		if valid && len(string) > len(result) {
			result = string
		}
	}
	return
}

1.215 - 2022-04-29 15:09:02 +0000 UTC

Longest Common Prefix

Code


import "fmt"


func substrings(input string) map[string]bool {
	results := make(map[string]bool)
	for index := range input {
		results[string(input[0:index+1])] = true
	}
	return results
}

func string_in_maps(
	source map[string]bool,
	target map[string]bool,
	results map[string]bool) {
	for string := range source {
		if result, exists_in_results := results[string]; exists_in_results && !result {
			continue
		}
		_, exists_in_target := target[string]
		results[string] = exists_in_target
	}
}

func longestCommonPrefix(strings []string) (result string) {
	results := make(map[string]bool)
	previous := make(map[string]bool)
	for index, string := range strings {
		current := substrings(string)
		if index == 0 {
			previous = current
		}
		string_in_maps(current, previous, results)
		string_in_maps(previous, current, results)
		fmt.Println("current string", string, current, "results", results)
		previous = current
	}
	for string, valid := range results {
		if !valid || len(string) < len(result) {
			continue
		}
		if len(string) == len(result) && string < result {
			result = string
			continue
		}
		result = string
	}
	fmt.Println("result", result)
	return
}

1.216 - 2022-04-28 06:04:20 +0000 UTC

Roman to Integer

Code

func romanToInt(input string) int {
	var result int
	types := map[rune]int{
		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
	}
	var previous rune
	for _, character := range input {
		result += types[character]
		switch {
		case previous == 'I' && (character == 'V' || character == 'X'):
			fallthrough
		case previous == 'X' && (character == 'L' || character == 'C'):
			fallthrough
		case previous == 'C' && (character == 'D' || character == 'M'):
			result -= types[previous] * 2
		}
		previous = character
	}
	return result
}

1.217 - 2022-04-28 05:59:35 +0000 UTC

Roman to Integer

Code


func in(character rune, targets string) bool {
	for _, target := range targets {
		if character == target {
			return true
		}
	}
	return false
}

func romanToInt(roman string) int {
	type dict map[rune]int
	var result int
	input := []rune(roman)
	types := dict{
		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
	}
	var previous rune
	for _, character := range input {
		result += types[character]
		switch {
		case previous == 'I' && in(character, "VX"):
			fallthrough
		case previous == 'X' && in(character, "LC"):
			fallthrough
		case previous == 'C' && in(character, "DM"):
			result -= types[previous] * 2
		}
		previous = character
	}
	return result
}

1.218 - 2022-04-28 05:59:06 +0000 UTC

Roman to Integer

Code


func in(character rune, targets string) bool {
	for _, target := range targets {
		if character == target {
			return true
		}
	}
	return false
}

func romanToInt(roman string) int {
	type dict map[rune]int
	var result int
	types := dict{
		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
	}
	for index, character := range roman {
		result += types[character]
        if index < 1 {
            continue}
        switch {
		case roman[index-1] == 'I' && in(character, "VX"):
			fallthrough
		case roman[index-1] == 'X' && in(character, "LC"):
			fallthrough
		case roman[index-1] == 'C' && in(character, "DM"):
			result -= types[rune(roman[index-1])] * 2
		}
	}
	return result
}

1.219 - 2022-04-28 05:55:16 +0000 UTC

Roman to Integer

Code


func in(character rune, targets string) bool {
	for _, target := range targets {
		if character == target {
			return true
		}
	}
	return false
}

func romanToInt(roman string) int {
	type dict map[rune]int
	var result int
	input := []rune(roman)
	types := dict{
		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
	}
	var previous rune
	for _, character := range input {
		result += types[character]
		switch {
		case previous == 'I' && in(character, "VX"):
			fallthrough
		case previous == 'X' && in(character, "LC"):
			fallthrough
		case previous == 'C' && in(character, "DM"):
			result -= types[previous] * 2
		}
		previous = character
	}
	return result
}

2 - Bazel shell worker

Bazel worker that runs shell commands

2.1 - Bazel targets

NameInfo
bazel-shell-worker
locationgo/bazel-shell-worker/BUILD.bazel:33:10
name//go/bazel-shell-worker:bazel-shell-worker
ruleClassgo_binary
visibility
  • //visibility:public
bazel-shell-worker_lib
locationgo/bazel-shell-worker/BUILD.bazel:16:11
name//go/bazel-shell-worker:bazel-shell-worker_lib
ruleClassgo_library
visibility
  • //visibility:private
changelog
locationgo/bazel-shell-worker/BUILD.bazel:11:17
name//go/bazel-shell-worker:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/bazel-shell-worker:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/bazel-shell-worker/BUILD.bazel:11:17
name//go/bazel-shell-worker:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/bazel-shell-worker:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/bazel-shell-worker/BUILD.bazel:11:17
name//go/bazel-shell-worker:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/bazel-shell-worker:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/bazel-shell-worker/BUILD.bazel:11:17
name//go/bazel-shell-worker:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/bazel-shell-worker:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/bazel-shell-worker/BUILD.bazel:11:17
name//go/bazel-shell-worker:changelog-template
ruleClass_write_file
ruleOutput
  • //go/bazel-shell-worker:changelog-template.md
visibility
  • //visibility:private
readme
locationgo/bazel-shell-worker/BUILD.bazel:6:10
name//go/bazel-shell-worker:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/bazel-shell-worker/BUILD.bazel:6:10
name//go/bazel-shell-worker:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/bazel-shell-worker:readme-children.tar
visibility
  • //visibility:public

2.2 - Changelog

3 - Bazel targets

NameInfo
changelog
locationgo/BUILD.bazel:10:17
name//go:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/BUILD.bazel:10:17
name//go:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/BUILD.bazel:10:17
name//go:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/BUILD.bazel:10:17
name//go:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/BUILD.bazel:10:17
name//go:changelog-template
ruleClass_write_file
ruleOutput
  • //go:changelog-template.md
visibility
  • //visibility:private
readme
locationgo/BUILD.bazel:5:10
name//go:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/BUILD.bazel:5:10
name//go:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go:readme-children.tar
visibility
  • //visibility:public

4 - Changelog

5 - File installer

CLI tool to install files

5.1 - Bazel targets

NameInfo
changelog
locationgo/file-installer/BUILD.bazel:11:17
name//go/file-installer:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/file-installer:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/file-installer/BUILD.bazel:11:17
name//go/file-installer:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/file-installer:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/file-installer/BUILD.bazel:11:17
name//go/file-installer:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/file-installer:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/file-installer/BUILD.bazel:11:17
name//go/file-installer:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/file-installer:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/file-installer/BUILD.bazel:11:17
name//go/file-installer:changelog-template
ruleClass_write_file
ruleOutput
  • //go/file-installer:changelog-template.md
visibility
  • //visibility:private
file-installer
locationgo/file-installer/BUILD.bazel:24:10
name//go/file-installer:file-installer
ruleClassgo_binary
visibility
  • //visibility:public
file-installer_lib
locationgo/file-installer/BUILD.bazel:16:11
name//go/file-installer:file-installer_lib
ruleClassgo_library
visibility
  • //visibility:private
readme
locationgo/file-installer/BUILD.bazel:6:10
name//go/file-installer:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/file-installer/BUILD.bazel:6:10
name//go/file-installer:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/file-installer:readme-children.tar
visibility
  • //visibility:public

5.2 - Changelog

5.3 - Cmd code for file-installer

5.3.1 - Bazel targets

NameInfo
changelog
locationgo/file-installer/cmd/BUILD.bazel:11:17
name//go/file-installer/cmd:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/file-installer/cmd:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/file-installer/cmd/BUILD.bazel:11:17
name//go/file-installer/cmd:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/file-installer/cmd:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/file-installer/cmd/BUILD.bazel:11:17
name//go/file-installer/cmd:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/file-installer/cmd:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/file-installer/cmd/BUILD.bazel:11:17
name//go/file-installer/cmd:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/file-installer/cmd:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/file-installer/cmd/BUILD.bazel:11:17
name//go/file-installer/cmd:changelog-template
ruleClass_write_file
ruleOutput
  • //go/file-installer/cmd:changelog-template.md
visibility
  • //visibility:private
cmd
locationgo/file-installer/cmd/BUILD.bazel:16:11
name//go/file-installer/cmd:cmd
ruleClassgo_library
visibility
  • //visibility:public
readme
locationgo/file-installer/cmd/BUILD.bazel:6:10
name//go/file-installer/cmd:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/file-installer/cmd/BUILD.bazel:6:10
name//go/file-installer/cmd:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/file-installer/cmd:readme-children.tar
visibility
  • //visibility:public

5.3.2 - Changelog

6 - Leetcode downloader

CLI app to download leetcode submissions

:warning: Download doesn’t work anymore because of Cloudflare

Usage

Generate submission from a submission file

bazel run go/leetcode-downloader -- \
    --submissions-file "${PWD}/out/submissions.json" \
    --root-dir "${PWD}" \
    generate

Help

Usage of flags:
  -base_url string
    	 (default "https://leetcode.com")
  -cookie string

  -limit uint
    	 (default 20)
  -offset uint

  -root-dir string
    	 (default "${PWD}")
  -submissions-file string

6.1 - Bazel targets

NameInfo
changelog
locationgo/leetcode-downloader/BUILD.bazel:11:17
name//go/leetcode-downloader:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/leetcode-downloader:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/leetcode-downloader/BUILD.bazel:11:17
name//go/leetcode-downloader:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/leetcode-downloader:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/leetcode-downloader/BUILD.bazel:11:17
name//go/leetcode-downloader:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/leetcode-downloader:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/leetcode-downloader/BUILD.bazel:11:17
name//go/leetcode-downloader:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/leetcode-downloader:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/leetcode-downloader/BUILD.bazel:11:17
name//go/leetcode-downloader:changelog-template
ruleClass_write_file
ruleOutput
  • //go/leetcode-downloader:changelog-template.md
visibility
  • //visibility:private
leetcode-downloader
locationgo/leetcode-downloader/BUILD.bazel:34:10
name//go/leetcode-downloader:leetcode-downloader
ruleClassgo_binary
visibility
  • //visibility:public
leetcode-downloader_lib
locationgo/leetcode-downloader/BUILD.bazel:16:11
name//go/leetcode-downloader:leetcode-downloader_lib
ruleClassgo_library
visibility
  • //visibility:private
readme
locationgo/leetcode-downloader/BUILD.bazel:6:10
name//go/leetcode-downloader:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/leetcode-downloader/BUILD.bazel:6:10
name//go/leetcode-downloader:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/leetcode-downloader:readme-children.tar
visibility
  • //visibility:public

6.2 - Changelog

6.3 - Models for leetcode-downloader

6.3.1 - Bazel targets

NameInfo
changelog
locationgo/leetcode-downloader/model/BUILD.bazel:11:17
name//go/leetcode-downloader/model:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/leetcode-downloader/model:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/leetcode-downloader/model/BUILD.bazel:11:17
name//go/leetcode-downloader/model:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/leetcode-downloader/model:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/leetcode-downloader/model/BUILD.bazel:11:17
name//go/leetcode-downloader/model:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/leetcode-downloader/model:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/leetcode-downloader/model/BUILD.bazel:11:17
name//go/leetcode-downloader/model:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/leetcode-downloader/model:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/leetcode-downloader/model/BUILD.bazel:11:17
name//go/leetcode-downloader/model:changelog-template
ruleClass_write_file
ruleOutput
  • //go/leetcode-downloader/model:changelog-template.md
visibility
  • //visibility:private
model
locationgo/leetcode-downloader/model/BUILD.bazel:16:11
name//go/leetcode-downloader/model:model
ruleClassgo_library
visibility
  • //visibility:public
readme
locationgo/leetcode-downloader/model/BUILD.bazel:6:10
name//go/leetcode-downloader/model:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/leetcode-downloader/model/BUILD.bazel:6:10
name//go/leetcode-downloader/model:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/leetcode-downloader/model:readme-children.tar
visibility
  • //visibility:public

6.3.2 - Changelog

7 - Readme tree

Tool to parse README.md files

Example

bazel run golang/readme-tree -- parse -g -C "${PWD}" .

7.1 - Bazel targets

NameInfo
changelog
locationgo/readme-tree/BUILD.bazel:11:17
name//go/readme-tree:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/readme-tree:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/readme-tree/BUILD.bazel:11:17
name//go/readme-tree:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/readme-tree:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/readme-tree/BUILD.bazel:11:17
name//go/readme-tree:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/readme-tree:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/readme-tree/BUILD.bazel:11:17
name//go/readme-tree:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/readme-tree:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/readme-tree/BUILD.bazel:11:17
name//go/readme-tree:changelog-template
ruleClass_write_file
ruleOutput
  • //go/readme-tree:changelog-template.md
visibility
  • //visibility:private
readme
locationgo/readme-tree/BUILD.bazel:6:10
name//go/readme-tree:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/readme-tree/BUILD.bazel:6:10
name//go/readme-tree:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/readme-tree:readme-children.tar
visibility
  • //visibility:public
readme-tree
locationgo/readme-tree/BUILD.bazel:34:10
name//go/readme-tree:readme-tree
ruleClassgo_binary
visibility
  • //visibility:public
readme-tree_lib
locationgo/readme-tree/BUILD.bazel:16:11
name//go/readme-tree:readme-tree_lib
ruleClassgo_library
visibility
  • //visibility:private

7.2 - Changelog

8 - Template files

Cli tool to template files

8.1 - Bazel targets

NameInfo
changelog
locationgo/template-files/BUILD.bazel:11:17
name//go/template-files:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/template-files:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/template-files/BUILD.bazel:11:17
name//go/template-files:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/template-files:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/template-files/BUILD.bazel:11:17
name//go/template-files:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/template-files:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/template-files/BUILD.bazel:11:17
name//go/template-files:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/template-files:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/template-files/BUILD.bazel:11:17
name//go/template-files:changelog-template
ruleClass_write_file
ruleOutput
  • //go/template-files:changelog-template.md
visibility
  • //visibility:private
readme
locationgo/template-files/BUILD.bazel:6:10
name//go/template-files:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/template-files/BUILD.bazel:6:10
name//go/template-files:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/template-files:readme-children.tar
visibility
  • //visibility:public
template-files
locationgo/template-files/BUILD.bazel:33:10
name//go/template-files:template-files
ruleClassgo_binary
visibility
  • //visibility:public
template-files_lib
locationgo/template-files/BUILD.bazel:16:11
name//go/template-files:template-files_lib
ruleClassgo_library
visibility
  • //visibility:private

8.2 - Changelog

9 - Utils

Random golang tools

9.1 - Bazel targets

NameInfo
changelog
locationgo/utils/BUILD.bazel:11:17
name//go/utils:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //go/utils:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationgo/utils/BUILD.bazel:11:17
name//go/utils:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //go/utils:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationgo/utils/BUILD.bazel:11:17
name//go/utils:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //go/utils:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationgo/utils/BUILD.bazel:11:17
name//go/utils:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/utils:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationgo/utils/BUILD.bazel:11:17
name//go/utils:changelog-template
ruleClass_write_file
ruleOutput
  • //go/utils:changelog-template.md
visibility
  • //visibility:private
readme
locationgo/utils/BUILD.bazel:6:10
name//go/utils:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationgo/utils/BUILD.bazel:6:10
name//go/utils:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //go/utils:readme-children.tar
visibility
  • //visibility:public
utils
locationgo/utils/BUILD.bazel:16:11
name//go/utils:utils
ruleClassgo_library
visibility
  • //visibility:public

9.2 - Changelog