ocaml: phase 5.1 merge_intervals.ml baseline (LeetCode #56, total length 9+3 = 12)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 50s

Sort intervals by start, then sweep maintaining a current (cs, ce)
window — extend ce if next start <= ce, else push current and start
fresh:

  let merge_intervals xs =
    let sorted = List.sort (fun (a, _) (b, _) -> a - b) xs in
    let rec aux acc cur xs =
      match xs with
      | [] -> List.rev (cur :: acc)
      | (s, e) :: rest ->
        let (cs, ce) = cur in
        if s <= ce then aux acc (cs, max e ce) rest
        else aux (cur :: acc) (s, e) rest
    in
    match sorted with
    | [] -> []
    | h :: rest -> aux [] h rest

  [(1,3);(2,6);(8,10);(15,18);(5,9)]
  -> [(1,10); (15,18)]
  total length = 9 + 3 = 12

Tests List.sort with custom comparator using tuple patterns, plus
tuple destructuring in lambda + let-tuple from accumulator + match
arms.

92 baseline programs total.
This commit is contained in:
2026-05-09 18:39:46 +00:00
parent df6efeb68e
commit 17a7a91d73
3 changed files with 30 additions and 0 deletions

View File

@@ -51,6 +51,7 @@
"levenshtein.ml": 11,
"memo_fib.ml": 75025,
"mortgage.ml": 1073,
"merge_intervals.ml": 12,
"merge_sort.ml": 44,
"merge_two.ml": 441,
"module_use.ml": 3,

View File

@@ -0,0 +1,21 @@
let merge_intervals xs =
let sorted = List.sort (fun (a, _) (b, _) -> a - b) xs in
let rec aux acc cur xs =
match xs with
| [] -> List.rev (cur :: acc)
| (s, e) :: rest ->
let (cs, ce) = cur in
if s <= ce then
let new_e = if e > ce then e else ce in
aux acc (cs, new_e) rest
else
aux (cur :: acc) (s, e) rest
in
match sorted with
| [] -> []
| h :: rest -> aux [] h rest
;;
let m = merge_intervals [(1, 3); (2, 6); (8, 10); (15, 18); (5, 9)] in
List.fold_left (fun acc (s, e) -> acc + e - s) 0 m