diff --git a/articles/count-connected-components.md b/articles/count-connected-components.md index 2b57b16dd..0f0dc28ba 100644 --- a/articles/count-connected-components.md +++ b/articles/count-connected-components.md @@ -165,6 +165,70 @@ public class Solution { } ``` +```go +func countComponents(n int, edges [][]int) int { + adj := make([][]int, n) + visit := make([]bool, n) + for _, edge := range edges { + u, v := edge[0], edge[1] + adj[u] = append(adj[u], v) + adj[v] = append(adj[v], u) + } + + var dfs func(int) + dfs = func(node int) { + for _, nei := range adj[node] { + if !visit[nei] { + visit[nei] = true + dfs(nei) + } + } + } + + res := 0 + for node := 0; node < n; node++ { + if !visit[node] { + visit[node] = true + dfs(node) + res++ + } + } + return res +} +``` + +```kotlin +class Solution { + fun countComponents(n: Int, edges: Array): Int { + val adj = Array(n) { mutableListOf() } + val visit = BooleanArray(n) + for ((u, v) in edges) { + adj[u].add(v) + adj[v].add(u) + } + + fun dfs(node: Int) { + for (nei in adj[node]) { + if (!visit[nei]) { + visit[nei] = true + dfs(nei) + } + } + } + + var res = 0 + for (node in 0 until n) { + if (!visit[node]) { + visit[node] = true + dfs(node) + res++ + } + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -369,6 +433,79 @@ public class Solution { } ``` +```go +func countComponents(n int, edges [][]int) int { + adj := make([][]int, n) + visit := make([]bool, n) + for _, edge := range edges { + u, v := edge[0], edge[1] + adj[u] = append(adj[u], v) + adj[v] = append(adj[v], u) + } + + bfs := func(node int) { + q := []int{node} + visit[node] = true + for len(q) > 0 { + cur := q[0] + q = q[1:] + for _, nei := range adj[cur] { + if !visit[nei] { + visit[nei] = true + q = append(q, nei) + } + } + } + } + + res := 0 + for node := 0; node < n; node++ { + if !visit[node] { + bfs(node) + res++ + } + } + return res +} +``` + +```kotlin +class Solution { + fun countComponents(n: Int, edges: Array): Int { + val adj = Array(n) { mutableListOf() } + val visit = BooleanArray(n) + for ((u, v) in edges) { + adj[u].add(v) + adj[v].add(u) + } + + fun bfs(node: Int) { + val q: Queue = LinkedList() + q.offer(node) + visit[node] = true + while (q.isNotEmpty()) { + val cur = q.poll() + for (nei in adj[cur]) { + if (!visit[nei]) { + visit[nei] = true + q.offer(nei) + } + } + } + } + + var res = 0 + for (node in 0 until n) { + if (!visit[node]) { + bfs(node) + res++ + } + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -641,6 +778,105 @@ public class Solution { } ``` +```go +type DSU struct { + parent []int + rank []int +} + +func NewDSU(n int) *DSU { + dsu := &DSU{ + parent: make([]int, n), + rank: make([]int, n), + } + for i := 0; i < n; i++ { + dsu.parent[i] = i + dsu.rank[i] = 1 + } + return dsu +} + +func (dsu *DSU) Find(node int) int { + cur := node + for cur != dsu.parent[cur] { + dsu.parent[cur] = dsu.parent[dsu.parent[cur]] + cur = dsu.parent[cur] + } + return cur +} + +func (dsu *DSU) Union(u, v int) bool { + pu := dsu.Find(u) + pv := dsu.Find(v) + if pu == pv { + return false + } + if dsu.rank[pv] > dsu.rank[pu] { + pu, pv = pv, pu + } + dsu.parent[pv] = pu + dsu.rank[pu] += dsu.rank[pv] + return true +} + +func countComponents(n int, edges [][]int) int { + dsu := NewDSU(n) + res := n + for _, edge := range edges { + u, v := edge[0], edge[1] + if dsu.Union(u, v) { + res-- + } + } + return res +} +``` + +```kotlin +class DSU(n: Int) { + val parent = IntArray(n) { it } + val rank = IntArray(n) { 1 } + + fun find(node: Int): Int { + var cur = node + while (cur != parent[cur]) { + parent[cur] = parent[parent[cur]] + cur = parent[cur] + } + return cur + } + + fun union(u: Int, v: Int): Boolean { + val pu = find(u) + val pv = find(v) + if (pu == pv) { + return false + } + if (rank[pv] > rank[pu]) { + parent[pu] = pv + } else { + parent[pv] = pu + rank[pu] += rank[pv] + } + return true + } +} + +class Solution { + fun countComponents(n: Int, edges: Array): Int { + val dsu = DSU(n) + var res = n + for (edge in edges) { + val (u, v) = edge + if (dsu.union(u, v)) { + res-- + } + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/counting-bits.md b/articles/counting-bits.md index a4135ebae..514bef953 100644 --- a/articles/counting-bits.md +++ b/articles/counting-bits.md @@ -86,6 +86,40 @@ public class Solution { } ``` +```go +func countBits(n int) []int { + res := make([]int, n+1) + for num := 0; num <= n; num++ { + one := 0 + for i := 0; i < 32; i++ { + if num&(1<> 1] + (i & 1) - return dp + return dp ``` ```java @@ -426,6 +540,28 @@ public class Solution { } ``` +```go +func countBits(n int) []int { + dp := make([]int, n+1) + for i := 1; i <= n; i++ { + dp[i] = dp[i >> 1] + (i&1); + } + return dp +} +``` + +```kotlin +class Solution { + fun countBits(n: Int): IntArray { + val dp = IntArray(n + 1) + for (i in 1..n) { + dp[i] = dp[i shr 1] + (i and 1) + } + return dp + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/foreign-dictionary.md b/articles/foreign-dictionary.md index 199b0b642..f1353b74a 100644 --- a/articles/foreign-dictionary.md +++ b/articles/foreign-dictionary.md @@ -282,6 +282,129 @@ public class Solution { } ``` +```go +func foreignDictionary(words []string) string { + adj := make(map[rune]map[rune]struct{}) + for _, w := range words { + for _, c := range w { + if _, exists := adj[c]; !exists { + adj[c] = make(map[rune]struct{}) + } + } + } + + for i := 0; i < len(words)-1; i++ { + w1, w2 := words[i], words[i+1] + minLen := len(w1) + if len(w2) < minLen { + minLen = len(w2) + } + if len(w1) > len(w2) && w1[:minLen] == w2[:minLen] { + return "" + } + for j := 0; j < minLen; j++ { + if w1[j] != w2[j] { + adj[rune(w1[j])][rune(w2[j])] = struct{}{} + break + } + } + } + + visited := make(map[rune]int) + var res []rune + + var dfs func(char rune) bool + dfs = func(char rune) bool { + if status, exists := visited[char]; exists { + return status == 1 + } + + visited[char] = 1 + + for neighChar := range adj[char] { + if dfs(neighChar) { + return true + } + } + + visited[char] = -1 + res = append(res, char) + return false + } + + for char := range adj { + if dfs(char) { + return "" + } + } + + var result []byte + for i := len(res) - 1; i >= 0; i-- { + result = append(result, byte(res[i])) + } + + return string(result) +} +``` + +```kotlin +class Solution { + fun foreignDictionary(words: Array): String { + val adj = HashMap>() + for (w in words) { + for (c in w) { + adj.putIfAbsent(c, hashSetOf()) + } + } + + for (i in 0 until words.size - 1) { + val w1 = words[i] + val w2 = words[i + 1] + val minLen = minOf(w1.length, w2.length) + if (w1.length > w2.length && + w1.substring(0, minLen) == w2.substring(0, minLen)) { + return "" + } + for (j in 0 until minLen) { + if (w1[j] != w2[j]) { + adj[w1[j]]?.add(w2[j]) + break + } + } + } + + val visited = HashMap() + val res = mutableListOf() + + fun dfs(char: Char): Boolean { + if (char in visited) { + return visited[char] == 1 + } + + visited[char] = 1 + + for (neighChar in adj[char] ?: emptySet()) { + if (dfs(neighChar)) { + return true + } + } + + visited[char] = -1 + res.add(char) + return false + } + + for (char in adj.keys) { + if (dfs(char)) { + return "" + } + } + + return res.reversed().joinToString("") + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -575,6 +698,131 @@ public class Solution { } ``` +```go +func foreignDictionary(words []string) string { + adj := make(map[byte]map[byte]struct{}) + indegree := make(map[byte]int) + + for _, word := range words { + for i := 0; i < len(word); i++ { + char := word[i] + if _, exists := adj[char]; !exists { + adj[char] = make(map[byte]struct{}) + } + indegree[char] = 0 + } + } + + for i := 0; i < len(words)-1; i++ { + w1, w2 := words[i], words[i+1] + minLen := len(w1) + if len(w2) < minLen { + minLen = len(w2) + } + + if len(w1) > len(w2) && w1[:minLen] == w2[:minLen] { + return "" + } + + for j := 0; j < minLen; j++ { + if w1[j] != w2[j] { + if _, exists := adj[w1[j]][w2[j]]; !exists { + adj[w1[j]][w2[j]] = struct{}{} + indegree[w2[j]]++ + } + break + } + } + } + + q := []byte{} + for char := range indegree { + if indegree[char] == 0 { + q = append(q, char) + } + } + + res := []byte{} + for len(q) > 0 { + char := q[0] + q = q[1:] + res = append(res, char) + + for neighbor := range adj[char] { + indegree[neighbor]-- + if indegree[neighbor] == 0 { + q = append(q, neighbor) + } + } + } + + if len(res) != len(indegree) { + return "" + } + + return string(res) +} +``` + +```kotlin +class Solution { + fun foreignDictionary(words: Array): String { + val adj = HashMap>() + val indegree = HashMap() + + for (word in words) { + for (c in word) { + adj.computeIfAbsent(c) { hashSetOf() } + indegree[c] = 0 + } + } + + for (i in 0 until words.size - 1) { + val w1 = words[i] + val w2 = words[i + 1] + val minLen = minOf(w1.length, w2.length) + + if (w1.length > w2.length && + w1.substring(0, minLen) == w2.substring(0, minLen)) { + return "" + } + + for (j in 0 until minLen) { + if (w1[j] != w2[j]) { + if (w2[j] !in adj[w1[j]]!!) { + adj[w1[j]]!!.add(w2[j]) + indegree[w2[j]] = indegree[w2[j]]!! + 1 + } + break + } + } + } + + val q: Queue = LinkedList() + for ((char, degree) in indegree) { + if (degree == 0) { + q.add(char) + } + } + + val res = StringBuilder() + while (q.isNotEmpty()) { + val char = q.poll() + res.append(char) + + for (neighbor in adj[char]!!) { + indegree[neighbor] = indegree[neighbor]!! - 1 + if (indegree[neighbor] == 0) { + q.add(neighbor) + } + } + } + + return if (res.length != indegree.size) "" else res.toString() + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/islands-and-treasure.md b/articles/islands-and-treasure.md index 69eae6e57..ff99ef107 100644 --- a/articles/islands-and-treasure.md +++ b/articles/islands-and-treasure.md @@ -208,6 +208,100 @@ public class Solution { } ``` +```go +func islandsAndTreasure(grid [][]int) { + rows, cols := len(grid), len(grid[0]) + directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} + INF := 2147483647 + visit := make([][]bool, rows) + for i := range visit { + visit[i] = make([]bool, cols) + } + + var dfs func(r, c int) int + dfs = func(r, c int) int { + if r < 0 || c < 0 || r >= rows || c >= cols || + grid[r][c] == -1 || visit[r][c] { + return INF + } + if grid[r][c] == 0 { + return 0 + } + + visit[r][c] = true + res := INF + for _, d := range directions { + dx, dy := d[0], d[1] + res = min(res, 1+dfs(r+dx, c+dy)) + } + visit[r][c] = false + return res + } + + for r := 0; r < rows; r++ { + for c := 0; c < cols; c++ { + if grid[r][c] == INF { + grid[r][c] = dfs(r, c) + } + } + } +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +```kotlin +class Solution { + private val directions = arrayOf( + intArrayOf(1, 0), intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1) + ) + private val INF = 2147483647 + private lateinit var visit: Array + private var rows = 0 + private var cols = 0 + + private fun dfs(grid: Array, r: Int, c: Int): Int { + if (r < 0 || c < 0 || r >= rows || c >= cols || + grid[r][c] == -1 || visit[r][c]) { + return INF + } + if (grid[r][c] == 0) { + return 0 + } + visit[r][c] = true + var res = INF + for (dir in directions) { + val cur = dfs(grid, r + dir[0], c + dir[1]) + if (cur != INF) { + res = minOf(res, 1 + cur) + } + } + visit[r][c] = false + return res + } + + fun islandsAndTreasure(grid: Array): Unit { + rows = grid.size + cols = grid[0].size + visit = Array(rows) { BooleanArray(cols) } + + for (r in 0 until rows) { + for (c in 0 until cols) { + if (grid[r][c] == INF) { + grid[r][c] = dfs(grid, r, c) + } + } + } + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -458,6 +552,105 @@ public class Solution { } ``` +```go +func islandsAndTreasure(grid [][]int) { + rows, cols := len(grid), len(grid[0]) + directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} + INF := 2147483647 + + bfs := func(r, c int) int { + q := [][2]int{{r, c}} + visit := make([][]bool, rows) + for i := range visit { + visit[i] = make([]bool, cols) + } + visit[r][c] = true + steps := 0 + + for len(q) > 0 { + size := len(q) + for i := 0; i < size; i++ { + current := q[0] + q = q[1:] + row, col := current[0], current[1] + if grid[row][col] == 0 { + return steps + } + for _, dir := range directions { + nr, nc := row+dir[0], col+dir[1] + if nr >= 0 && nc >= 0 && nr < rows && nc < cols && + !visit[nr][nc] && grid[nr][nc] != -1 { + visit[nr][nc] = true + q = append(q, [2]int{nr, nc}) + } + } + } + steps++ + } + return INF + } + + for r := 0; r < rows; r++ { + for c := 0; c < cols; c++ { + if grid[r][c] == INF { + grid[r][c] = bfs(r, c) + } + } + } +} +``` + +```kotlin +class Solution { + private val directions = arrayOf( + intArrayOf(1, 0), intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1) + ) + private val INF = 2147483647 + + fun islandsAndTreasure(grid: Array): Unit { + val rows = grid.size + val cols = grid[0].size + + fun bfs(r: Int, c: Int): Int { + val q = ArrayDeque>() + q.add(Pair(r, c)) + val visit = Array(rows) { BooleanArray(cols) } + visit[r][c] = true + var steps = 0 + + while (q.isNotEmpty()) { + repeat(q.size) { + val (row, col) = q.removeFirst() + if (grid[row][col] == 0) { + return steps + } + for (dir in directions) { + val nr = row + dir[0] + val nc = col + dir[1] + if (nr in 0 until rows && nc in 0 until cols && + !visit[nr][nc] && grid[nr][nc] != -1) { + visit[nr][nc] = true + q.add(Pair(nr, nc)) + } + } + } + steps++ + } + return INF + } + + for (r in 0 until rows) { + for (c in 0 until cols) { + if (grid[r][c] == INF) { + grid[r][c] = bfs(r, c) + } + } + } + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -671,6 +864,80 @@ public class Solution { } ``` +```go +func islandsAndTreasure(grid [][]int) { + m, n := len(grid), len(grid[0]) + q := [][2]int{} + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == 0 { + q = append(q, [2]int{i, j}) + } + } + } + if len(q) == 0 { + return + } + + dirs := [][]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + + for len(q) > 0 { + node := q[0] + q = q[1:] + row, col := node[0], node[1] + + for _, dir := range dirs { + r, c := row+dir[0], col+dir[1] + if r >= m || c >= n || r < 0 || c < 0 || + grid[r][c] != 2147483647 { + continue + } + q = append(q, [2]int{r, c}) + grid[r][c] = grid[row][col] + 1 + } + } +} +``` + +```kotlin +class Solution { + fun islandsAndTreasure(grid: Array): Unit { + val m = grid.size + val n = grid[0].size + val q: Queue> = LinkedList() + + for (i in 0 until m) { + for (j in 0 until n) { + if (grid[i][j] == 0) { + q.add(Pair(i, j)) + } + } + } + if (q.isEmpty()) return + + val dirs = arrayOf( + intArrayOf(-1, 0), intArrayOf(0, -1), + intArrayOf(1, 0), intArrayOf(0, 1) + ) + + while (q.isNotEmpty()) { + val (row, col) = q.poll() + for (dir in dirs) { + val r = row + dir[0] + val c = col + dir[1] + if (r !in 0 until m || c !in 0 until n || + grid[r][c] != Int.MAX_VALUE) { + continue + } + q.add(Pair(r, c)) + grid[r][c] = grid[row][col] + 1 + } + } + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/meeting-schedule-ii.md b/articles/meeting-schedule-ii.md index 1d41af505..ce53b1e92 100644 --- a/articles/meeting-schedule-ii.md +++ b/articles/meeting-schedule-ii.md @@ -141,6 +141,58 @@ public class Solution { } ``` +```go +/** + * Definition of Interval: + * type Interval struct { + * start int + * end int + * } + */ + +func minMeetingRooms(intervals []Interval) int { + sort.Slice(intervals, func(i, j int) bool { + return intervals[i].start < intervals[j].start + }) + + pq := priorityqueue.NewWith(utils.IntComparator) + + for _, interval := range intervals { + if pq.Size() > 0 { + if top, _ := pq.Peek(); top.(int) <= interval.start { + pq.Dequeue() + } + } + pq.Enqueue(interval.end) + } + + return pq.Size() +} +``` + +```kotlin +/** + * Definition of Interval: + * class Interval(var start: Int, var end: Int) {} + */ + +class Solution { + fun minMeetingRooms(intervals: List): Int { + intervals.sortBy { it.start } + + val minHeap = PriorityQueue() + for (interval in intervals) { + if (minHeap.isNotEmpty() && minHeap.peek() <= interval.start) { + minHeap.poll() + } + minHeap.add(interval.end) + } + + return minHeap.size + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -302,6 +354,66 @@ public class Solution { } ``` +```go +/** + * Definition of Interval: + * type Interval struct { + * start int + * end int + * } + */ + +func minMeetingRooms(intervals []Interval) int { + mp := make(map[int]int) + for _, i := range intervals { + mp[i.start]++ + mp[i.end]-- + } + + keys := make([]int, 0, len(mp)) + for k := range mp { + keys = append(keys, k) + } + sort.Ints(keys) + + prev := 0 + res := 0 + for _, k := range keys { + prev += mp[k] + if prev > res { + res = prev + } + } + return res +} +``` + +```kotlin +/** + * Definition of Interval: + * class Interval(var start: Int, var end: Int) {} + */ + +class Solution { + fun minMeetingRooms(intervals: List): Int { + val mp = HashMap() + for (i in intervals) { + mp[i.start] = mp.getOrDefault(i.start, 0) + 1 + mp[i.end] = mp.getOrDefault(i.end, 0) - 1 + } + + val keys = mp.keys.sorted() + var prev = 0 + var res = 0 + for (k in keys) { + prev += mp[k]!! + res = maxOf(res, prev) + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -504,6 +616,79 @@ public class Solution { } ``` +```go +/** + * Definition of Interval: + * type Interval struct { + * start int + * end int + * } + */ + +func minMeetingRooms(intervals []Interval) int { + start := make([]int, len(intervals)) + end := make([]int, len(intervals)) + + for i, interval := range intervals { + start[i] = interval.start + end[i] = interval.end + } + + sort.Ints(start) + sort.Ints(end) + + res, count := 0, 0 + s, e := 0, 0 + + for s < len(intervals) { + if start[s] < end[e] { + s++ + count++ + } else { + e++ + count-- + } + if count > res { + res = count + } + } + + return res +} +``` + +```kotlin +/** + * Definition of Interval: + * class Interval(var start: Int, var end: Int) {} + */ + +class Solution { + fun minMeetingRooms(intervals: List): Int { + val start = intervals.map { it.start }.sorted() + val end = intervals.map { it.end }.sorted() + + var res = 0 + var count = 0 + var s = 0 + var e = 0 + + while (s < intervals.size) { + if (start[s] < end[e]) { + s++ + count++ + } else { + e++ + count-- + } + res = maxOf(res, count) + } + + return res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -543,6 +728,17 @@ class Solution: ``` ```java +/** + * Definition of Interval: + * public class Interval { + * public int start, end; + * public Interval(int start, int end) { + * this.start = start; + * this.end = end; + * } + * } + */ + public class Solution { public int minMeetingRooms(List intervals) { List time = new ArrayList<>(); @@ -668,6 +864,71 @@ public class Solution { } ``` +```go +/** + * Definition of Interval: + * type Interval struct { + * start int + * end int + * } + */ + +func minMeetingRooms(intervals []Interval) int { + var time [][]int + for _, i := range intervals { + time = append(time, []int{i.start, 1}) + time = append(time, []int{i.end, -1}) + } + + sort.Slice(time, func(i, j int) bool { + if time[i][0] == time[j][0] { + return time[i][1] < time[j][1] + } + return time[i][0] < time[j][0] + }) + + res, count := 0, 0 + for _, t := range time { + count += t[1] + if count > res { + res = count + } + } + return res +} +``` + +```kotlin +/** + * Definition of Interval: + * class Interval(var start: Int, var end: Int) {} + */ + +class Solution { + fun minMeetingRooms(intervals: Array): Int { + val time = mutableListOf>() + + for (i in intervals) { + time.add(Pair(i.start, 1)) + time.add(Pair(i.end, -1)) + } + + time.sortWith(compareBy> { it.first } + .thenBy { it.second }) + + var res = 0 + var count = 0 + + for (t in time) { + count += t.second + res = maxOf(res, count) + } + + return res + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/meeting-schedule.md b/articles/meeting-schedule.md index b4e32f6fc..735df876a 100644 --- a/articles/meeting-schedule.md +++ b/articles/meeting-schedule.md @@ -144,6 +144,67 @@ public class Solution { } ``` +```go +/** + * Definition of Interval: + * type Interval struct { + * start int + * end int + * } + */ + +func canAttendMeetings(intervals []Interval) bool { + n := len(intervals) + for i := 0; i < n; i++ { + A := intervals[i] + for j := i + 1; j < n; j++ { + B := intervals[j] + if min(A.end, B.end) > max(A.start, B.start) { + return false + } + } + } + return true +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +```kotlin +/** + * Definition of Interval: + * class Interval(var start: Int, var end: Int) {} + */ + +class Solution { + fun canAttendMeetings(intervals: List): Boolean { + val n = intervals.size + for (i in 0 until n) { + val A = intervals[i] + for (j in i + 1 until n) { + val B = intervals[j] + if (minOf(A.end, B.end) > maxOf(A.start, B.start)) { + return false + } + } + } + return true + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -296,6 +357,49 @@ public class Solution { } ``` +```go +/** +* Definition of Interval: +* type Interval struct { +* start int +* end int +* } +*/ + +func canAttendMeetings(intervals []Interval) bool { + sort.Slice(intervals, func(i, j int) bool { + return intervals[i].start < intervals[j].start + }) + + for i := 1; i < len(intervals); i++ { + if intervals[i-1].end > intervals[i].start { + return false + } + } + return true +} +``` + +```kotlin +/** + * Definition of Interval: + * class Interval(var start: Int, var end: Int) {} + */ + +class Solution { + fun canAttendMeetings(intervals: List): Boolean { + intervals.sortedBy { it.start }.let { + for (i in 1 until it.size) { + if (it[i - 1].end > it[i].start) { + return false + } + } + } + return true + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/missing-number.md b/articles/missing-number.md index a1307153d..0ddb891db 100644 --- a/articles/missing-number.md +++ b/articles/missing-number.md @@ -78,6 +78,34 @@ public class Solution { } ``` +```go +func missingNumber(nums []int) int { + n := len(nums) + sort.Ints(nums) + for i := 0; i < n; i++ { + if nums[i] != i { + return i + } + } + return n +} +``` + +```kotlin +class Solution { + fun missingNumber(nums: IntArray): Int { + val n = nums.size + nums.sort() + for (i in 0 until n) { + if (nums[i] != i) { + return i + } + } + return n + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -168,6 +196,37 @@ public class Solution { } ``` +```go +func missingNumber(nums []int) int { + numSet := make(map[int]struct{}) + for _, num := range nums { + numSet[num] = struct{}{} + } + n := len(nums) + for i := 0; i <= n; i++ { + if _, exists := numSet[i]; !exists { + return i + } + } + return -1 +} +``` + +```kotlin +class Solution { + fun missingNumber(nums: IntArray): Int { + val numSet = nums.toSet() + val n = nums.size + for (i in 0..n) { + if (i !in numSet) { + return i + } + } + return -1 + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -248,6 +307,30 @@ public class Solution { } ``` +```go +func missingNumber(nums []int) int { + n := len(nums) + xorr := n + for i := 0; i < n; i++ { + xorr ^= i ^ nums[i] + } + return xorr +} +``` + +```kotlin +class Solution { + fun missingNumber(nums: IntArray): Int { + val n = nums.size + var xorr = n + for (i in 0 until n) { + xorr = xorr xor i xor nums[i] + } + return xorr + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -328,6 +411,28 @@ public class Solution { } ``` +```go +func missingNumber(nums []int) int { + res := len(nums) + for i := 0; i < len(nums); i++ { + res += i - nums[i] + } + return res +} +``` + +```kotlin +class Solution { + fun missingNumber(nums: IntArray): Int { + var res = nums.size + for (i in nums.indices) { + res += i - nums[i] + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/reverse-integer.md b/articles/reverse-integer.md index d5a9d306b..f6d060a33 100644 --- a/articles/reverse-integer.md +++ b/articles/reverse-integer.md @@ -96,6 +96,57 @@ public class Solution { } ``` +```go +func reverse(x int) int { + org := x + x = abs(x) + res := 0 + + for x > 0 { + res = res*10 + x%10 + x /= 10 + } + + if org < 0 { + res = -res + } + if res < -(1 << 31) || res > (1<<31)-1 { + return 0 + } + return res +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +```kotlin +class Solution { + fun reverse(x: Int): Int { + val org = x + var num = Math.abs(x) + var res = 0 + + while (num > 0) { + if (res > (Int.MAX_VALUE - num % 10) / 10) { + return 0 + } + res = res * 10 + num % 10 + num /= 10 + } + + if (org < 0) { + res = -res + } + return if (res < Int.MIN_VALUE || res > Int.MAX_VALUE) 0 else res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -220,6 +271,45 @@ public class Solution { } ``` +```go +func reverse(x int) int { + var rec func(int, int) int + rec = func(n, rev int) int { + if n == 0 { + return rev + } + rev = rev*10 + n%10 + return rec(n/10, rev) + } + + sign := 1 + if x < 0 { + sign = -1 + x = -x + } + + reversedNum := rec(x, 0) * sign + if reversedNum < -(1<<31) || reversedNum > (1<<31)-1 { + return 0 + } + return reversedNum +} +``` + +```kotlin +class Solution { + fun reverse(x: Int): Int { + val res = rec(Math.abs(x), 0L) * if (x < 0) -1 else 1 + return if (res < Int.MIN_VALUE || res > Int.MAX_VALUE) 0 else res.toInt() + } + + private fun rec(n: Int, rev: Long): Long { + if (n == 0) return rev + return rec(n / 10, rev * 10 + n % 10) + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -350,6 +440,55 @@ public class Solution { } ``` +```go +func reverse(x int) int { + MIN := -2147483648 // -2^31 + MAX := 2147483647 // 2^31 - 1 + + res := 0 + for x != 0 { + digit := int(math.Mod(float64(x), 10)) + x = int(float64(x) / 10) + + if res > MAX/10 || (res == MAX/10 && digit > MAX%10) { + return 0 + } + if res < MIN/10 || (res == MIN/10 && digit < MIN%10) { + return 0 + } + res = (res * 10) + digit + } + + return res +} +``` + +```kotlin +class Solution { + fun reverse(x: Int): Int { + val MIN = -2147483648 // -2^31 + val MAX = 2147483647 // 2^31 - 1 + + var res = 0 + var num = x + while (num != 0) { + val digit = (num % 10).toInt() + num /= 10 + + if (res > MAX / 10 || (res == MAX / 10 && digit > MAX % 10)) { + return 0 + } + if (res < MIN / 10 || (res == MIN / 10 && digit < MIN % 10)) { + return 0 + } + res = res * 10 + digit + } + + return res + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/string-encode-and-decode.md b/articles/string-encode-and-decode.md index 8b02832fb..c0cad7e12 100644 --- a/articles/string-encode-and-decode.md +++ b/articles/string-encode-and-decode.md @@ -220,6 +220,68 @@ public class Solution { } ``` +```go +type Solution struct{} + +func (s *Solution) Encode(strs []string) string { + if len(strs) == 0 { + return "" + } + var sizes []string + for _, str := range strs { + sizes = append(sizes, strconv.Itoa(len(str))) + } + return strings.Join(sizes, ",") + "#" + strings.Join(strs, "") +} + +func (s *Solution) Decode(encoded string) []string { + if encoded == "" { + return []string{} + } + parts := strings.SplitN(encoded, "#", 2) + sizes := strings.Split(parts[0], ",") + var res []string + i := 0 + for _, sz := range sizes { + if sz == "" { + continue + } + length, _ := strconv.Atoi(sz) + res = append(res, parts[1][i:i+length]) + i += length + } + return res +} +``` + +```kotlin +class Solution { + fun encode(strs: List): String { + if (strs.isEmpty()) return "" + val sizes = mutableListOf() + for (str in strs) { + sizes.add(str.length.toString()) + } + return sizes.joinToString(",") + "#" + strs.joinToString("") + } + + fun decode(encoded: String): List { + if (encoded.isEmpty()) return emptyList() + val parts = encoded.split("#", limit = 2) + val sizes = parts[0].split(",") + val res = mutableListOf() + var i = 0 + for (sz in sizes) { + if (sz.isEmpty()) continue + val length = sz.toInt() + res.add(parts[1].substring(i, i + length)) + i += length + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -387,6 +449,63 @@ public class Solution { } ``` +```go +type Solution struct{} + +func (s *Solution) Encode(strs []string) string { + res := "" + for _, str := range strs { + res += strconv.Itoa(len(str)) + "#" + str + } + return res +} + +func (s *Solution) Decode(encoded string) []string { + res := []string{} + i := 0 + for i < len(encoded) { + j := i + for encoded[j] != '#' { + j++ + } + length, _ := strconv.Atoi(encoded[i:j]) + i = j + 1 + res = append(res, encoded[i:i+length]) + i += length + } + return res +} +``` + +```kotlin +class Solution { + + fun encode(strs: List): String { + val res = StringBuilder() + for (str in strs) { + res.append(str.length).append('#').append(str) + } + return res.toString() + } + + fun decode(encoded: String): List { + val res = mutableListOf() + var i = 0 + while (i < encoded.length) { + var j = i + while (encoded[j] != '#') { + j++ + } + val length = encoded.substring(i, j).toInt() + i = j + 1 + res.add(encoded.substring(i, i + length)) + i += length + } + return res + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/sum-of-two-integers.md b/articles/sum-of-two-integers.md index 7212f1fc1..4fffcb35f 100644 --- a/articles/sum-of-two-integers.md +++ b/articles/sum-of-two-integers.md @@ -46,6 +46,20 @@ public class Solution { } ``` +```go +func getSum(a int, b int) int { + return a + b +} +``` + +```kotlin +class Solution { + fun getSum(a: Int, b: Int): Int { + return a + b + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -182,6 +196,60 @@ public class Solution { } ``` +```go +func getSum(a int, b int) int { + carry := 0 + res := 0 + mask := 0xFFFFFFFF + + for i := 0; i < 32; i++ { + aBit := (a >> i) & 1 + bBit := (b >> i) & 1 + curBit := aBit ^ bBit ^ carry + if (aBit + bBit + carry) >= 2 { + carry = 1 + } else { + carry = 0 + } + if curBit == 1 { + res |= (1 << i) + } + } + + if res > 0x7FFFFFFF { + res = ^(res ^ mask) + } + + return res +} +``` + +```kotlin +class Solution { + fun getSum(a: Int, b: Int): Int { + var carry = 0 + var res = 0 + val mask = 0xFFFFFFFF.toInt() + + for (i in 0 until 32) { + val aBit = (a shr i) and 1 + val bBit = (b shr i) and 1 + val curBit = aBit xor bBit xor carry + carry = if (aBit + bBit + carry >= 2) 1 else 0 + if (curBit == 1) { + res = res or (1 shl i) + } + } + + if (res > 0x7FFFFFFF) { + res = res.inv() xor mask + } + + return res + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -267,6 +335,50 @@ public class Solution { } ``` +```go +func getSum(a int, b int) int { + mask := 0xFFFFFFFF + maxInt := 0x7FFFFFFF + + for b != 0 { + carry := (a & b) << 1 + a = (a ^ b) & mask + b = carry & mask + } + + if a <= maxInt { + return a + } + return ^(a ^ mask) +} +``` + +```kotlin +class Solution { + fun getSum(a: Int, b: Int): Int { + var carry = 0 + var res = 0 + val mask = 0xFFFFFFFF.toInt() + + for (i in 0 until 32) { + val aBit = (a shr i) and 1 + val bBit = (b shr i) and 1 + val curBit = aBit xor bBit xor carry + carry = if (aBit + bBit + carry >= 2) 1 else 0 + if (curBit == 1) { + res = res or (1 shl i) + } + } + + if (res > 0x7FFFFFFF) { + res = res.inv() xor mask + } + + return res + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/valid-tree.md b/articles/valid-tree.md index d4c8ea3c6..a343b676e 100644 --- a/articles/valid-tree.md +++ b/articles/valid-tree.md @@ -203,6 +203,69 @@ public class Solution { } ``` +```go +func validTree(n int, edges [][]int) bool { + if len(edges) > n-1 { + return false + } + + adj := make([][]int, n) + for _, edge := range edges { + u, v := edge[0], edge[1] + adj[u] = append(adj[u], v) + adj[v] = append(adj[v], u) + } + + visit := make(map[int]bool) + var dfs func(node, parent int) bool + dfs = func(node, parent int) bool { + if visit[node] { + return false + } + visit[node] = true + for _, nei := range adj[node] { + if nei == parent { + continue + } + if !dfs(nei, node) { + return false + } + } + return true + } + + return dfs(0, -1) && len(visit) == n +} +``` + +```kotlin +class Solution { + fun validTree(n: Int, edges: Array): Boolean { + if (edges.size > n - 1) return false + + val adj = Array(n) { mutableListOf() } + for ((u, v) in edges) { + adj[u].add(v) + adj[v].add(u) + } + + val visit = HashSet() + + fun dfs(node: Int, parent: Int): Boolean { + if (node in visit) return false + visit.add(node) + for (nei in adj[node]) { + if (nei == parent) continue + if (!dfs(nei, node)) return false + } + return true + } + + return dfs(0, -1) && visit.size == n + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -405,6 +468,75 @@ public class Solution { } ``` +```go +func validTree(n int, edges [][]int) bool { + if len(edges) > n-1 { + return false + } + + adj := make([][]int, n) + for _, edge := range edges { + u, v := edge[0], edge[1] + adj[u] = append(adj[u], v) + adj[v] = append(adj[v], u) + } + + visit := make(map[int]bool) + q := [][2]int{{0, -1}} // (current node, parent node) + visit[0] = true + + for len(q) > 0 { + node, parent := q[0][0], q[0][1] + q = q[1:] + + for _, nei := range adj[node] { + if nei == parent { + continue + } + if visit[nei] { + return false + } + visit[nei] = true + q = append(q, [2]int{nei, node}) + } + } + + return len(visit) == n +} +``` + +```kotlin +class Solution { + fun validTree(n: Int, edges: Array): Boolean { + if (edges.size > n - 1) return false + + val adj = Array(n) { mutableListOf() } + for ((u, v) in edges) { + adj[u].add(v) + adj[v].add(u) + } + + val visit = mutableSetOf() + val q: Queue> = LinkedList() // Queue of (node, parent) + q.offer(0 to -1) + visit.add(0) + + while (q.isNotEmpty()) { + val (node, parent) = q.poll() + + for (nei in adj[node]) { + if (nei == parent) continue + if (nei in visit) return false + visit.add(nei) + q.offer(nei to node) + } + } + + return visit.size == n + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -700,6 +832,106 @@ public class Solution { } ``` +```go +type DSU struct { + Parent []int + Size []int + Comps int +} + +func NewDSU(n int) *DSU { + parent := make([]int, n+1) + size := make([]int, n+1) + for i := 0; i <= n; i++ { + parent[i] = i + size[i] = 1 + } + return &DSU{Parent: parent, Size: size, Comps: n} +} + +func (dsu *DSU) Find(node int) int { + if dsu.Parent[node] != node { + dsu.Parent[node] = dsu.Find(dsu.Parent[node]) + } + return dsu.Parent[node] +} + +func (dsu *DSU) Union(u, v int) bool { + pu, pv := dsu.Find(u), dsu.Find(v) + if pu == pv { + return false + } + dsu.Comps-- + if dsu.Size[pu] < dsu.Size[pv] { + pu, pv = pv, pu + } + dsu.Size[pu] += dsu.Size[pv] + dsu.Parent[pv] = pu + return true +} + +func (dsu *DSU) Components() int { + return dsu.Comps +} + +func validTree(n int, edges [][]int) bool { + if len(edges) > n-1 { + return false + } + dsu := NewDSU(n) + for _, edge := range edges { + if !dsu.Union(edge[0], edge[1]) { + return false + } + } + return dsu.Components() == 1 +} +``` + +```kotlin +class DSU(n: Int) { + private val parent = IntArray(n + 1) { it } + private val size = IntArray(n + 1) { 1 } + var comps = n + private set + + fun find(node: Int): Int { + if (parent[node] != node) { + parent[node] = find(parent[node]) + } + return parent[node] + } + + fun union(u: Int, v: Int): Boolean { + val pu = find(u) + val pv = find(v) + if (pu == pv) return false + + comps-- + if (size[pu] < size[pv]) { + parent[pu] = pv + size[pv] += size[pu] + } else { + parent[pv] = pu + size[pu] += size[pv] + } + return true + } +} + +class Solution { + fun validTree(n: Int, edges: Array): Boolean { + if (edges.size > n - 1) return false + + val dsu = DSU(n) + for ((u, v) in edges) { + if (!dsu.union(u, v)) return false + } + return dsu.comps == 1 + } +} +``` + ::tabs-end ### Time & Space Complexity