Skip to content

perf(LCS): find the candidate to extend by binary search - #89

Merged
bhousel merged 1 commit into
bhousel:mainfrom
seking:lcs-binary-search
Nov 12, 2026
Merged

bhousel merged 1 commit into
bhousel:mainfrom
seking:lcs-binary-search

Conversation

@seking

@seking seking commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Fixes the slowdown in #84 for inputs with many equal lines, such as text with many blank lines.

In LCS, the candidate that j extends was found by a linear scan from r. The buffer2index values from r on are strictly increasing, so the same candidate can be found by binary search. The output is unchanged.

Measured on a 4,000-line text that is 45% blank lines, with five changes on each side: 11.2 s before, 0.15 s after. I compared the output with 3.2.1 on 50,000 small inputs and three large ones, and it was identical in every case.

The worst case left is a large input of only one repeated line (20,000 blank lines still takes about 17 s).

The scan over `candidates` made LCS quadratic for inputs with many equal
elements, such as text with many blank lines (bhousel#84). The `buffer2index`
values from `r` on are strictly increasing, so the same candidate is found
by binary search. The results are unchanged.
@bhousel

bhousel commented Nov 12, 2026

Copy link
Copy Markdown
Owner

Thanks @seking, this is a great find! I checked it against 3.2.1 on 50k random inputs (lots of blank and repeated lines) and the output is identical, and a 4,000-line case went from 4.6 s to 40 ms. Merging.

@bhousel
bhousel merged commit 4c74dd6 into bhousel:main Nov 12, 2026
1 check passed
bhousel added a commit that referenced this pull request Nov 12, 2026
(closes: #50, re: #89)

- diffComm: the empty-lines example from #50
- LCS: check against a brute-force LCS on mostly-blank random inputs
- LCS: regression test with a timeout for large inputs with many empty lines

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

2 participants