My O(n ) Algorithm Ran in O(n) — and Why That Meant My Stress Test Was Wrong
For my algorithms course, I solved three variants of the text segmentation problem with dynamic programming, proved them correct, and stress-tested them. The most useful part wasn't the algorithms. It was looking at my stress test results and realising one of them made no sense. The problem You get a string of letters with no spaces, and a function IsWord(s) that tells you whether s is a valid…
The student completed three variants of the text segmentation problem using dynamic programming. The first variant counted the ways to split a string into words. The second variant checked whether two strings could be split at the same positions. The third variant counted the ways to split two strings at the same positions, but aimed to minimize the number of dictionary lookups.
The student simulated the worst-case scenario by making the IsWord function always return True. This resulted in O(n²) calls to IsWord. The stress test showed that variant (b) was significantly faster than the others, with a linear growth rate, contrary to the O(n²) expectation.
The student discovered that the inner loop only required a single check for the first word in each iteration. By moving this cheap check first in the boolean condition, the number of IsWord calls was reduced. In the case where no substring was a word, the number of IsWord calls dropped from 2,001,000 to 2,000.
Additionally, the number of splits for an n-letter string with every substring being a word is 2ⁿ⁻¹. At n = 2,000, this results in a 2,000-bit integer. The algorithm also copies characters during slicing, making the "O(n²)" analysis misleading as it assumes O(1) operations for additions and slicing.
The student learned the importance of verifying that the worst-case test is indeed the worst case, analyzing which input makes each loop run longest, measuring the operation of interest rather than relying solely on wall-clock time, and considering the order of boolean conditions.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to