Skip to content

Commit

Permalink
Merge pull request neetcode-gh#514 from ChrisKheng/main
Browse files Browse the repository at this point in the history
Add scala and go solution for 56-Merge-Intervals
  • Loading branch information
Ahmad-A0 authored Jul 21, 2022
2 parents e95a2ad + 77ae395 commit c70be8f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
27 changes: 27 additions & 0 deletions go/56-Merge-Intervals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import "sort"

func merge(intervals [][]int) [][]int {
const (
start = 0
end = 1
)

sort.SliceStable(intervals, func(i, j int) bool {
return intervals[i][start] < intervals[j][start]
})

res := [][]int{intervals[0]}
for i := 1; i < len(intervals); i++ {
currResLastIndex := len(res) - 1
currEnd := res[currResLastIndex]
curr := intervals[i]

if currEnd[end] < curr[start] {
res = append(res, curr)
} else if currEnd[end] < curr[end] {
res[currResLastIndex][end] = curr[end]
}
}

return res
}
23 changes: 23 additions & 0 deletions scala/56-Merge-Intervals.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import scala.collection.mutable.ArrayBuffer

object Solution {
def merge(intervals: Array[Array[Int]]): Array[Array[Int]] = {
val (start, end) = (0, 1)
val sortedIntervals = intervals.sortBy(_(start))
val res = ArrayBuffer[Array[Int]](sortedIntervals(0))

for (i <- 1 until sortedIntervals.length) {
val currEndIdx = res.size - 1
val currEnd = res(currEndIdx)
val curr = sortedIntervals(i)

if (currEnd(end) < curr(start)) {
res += curr
} else {
res(currEndIdx)(end) = currEnd(end).max(curr(end))
}
}

return res.toArray
}
}

0 comments on commit c70be8f

Please sign in to comment.