Skip to content

Replace O(n^2) interval merging with sort-then-merge#15

Merged
andrew merged 1 commit into
mainfrom
fix/merge-intervals-performance
May 2, 2026
Merged

Replace O(n^2) interval merging with sort-then-merge#15
andrew merged 1 commit into
mainfrom
fix/merge-intervals-performance

Conversation

@andrew
Copy link
Copy Markdown
Contributor

@andrew andrew commented May 2, 2026

`mergeIntervals` used a nested loop to find merge candidates, making it O(n^2). Combined with the iterative `result.Union(r)` pattern in npm `||` and hex `or` parsing, this produced O(n^3) total time for constraint strings with many disjunctions.

Two changes:

  • `mergeIntervals` now sorts intervals by lower bound and merges in a single linear pass, reducing it to O(n log n)
  • npm `||` and hex `or` parsing collect all intervals first and merge once, instead of calling `Union` incrementally

mergeIntervals used a nested loop to find merge candidates, making
union-heavy operations cubic when combined with iterative Union calls
in npm || and hex or parsing. Now sorts intervals by lower bound
and merges in a single linear pass. The npm and hex parsers also
collect all intervals first instead of merging incrementally.
@andrew andrew merged commit 35a2e42 into main May 2, 2026
2 checks passed
@andrew andrew deleted the fix/merge-intervals-performance branch May 2, 2026 15:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant