Skip to content

Stop the cost model calling merge sort, binary search and tree walks exponential - #3

Merged
ethanzhoucool merged 2 commits into
mainfrom
claude/fix-cost-model
Nov 3, 2026
Merged

ethanzhoucool merged 2 commits into
mainfrom
claude/fix-cost-model

Conversation

@ethanzhoucool

Copy link
Copy Markdown
Owner

Summary

The asymptotic-cost heuristic labelled almost every recursive function that has two self-calls as O(2^n). That label also produces a high-severity "Exponential recursion" finding that tells the reader to memoise the function. In practice it fired on the textbook recursion people paste into an explainer:

function before after
recursive binary search (one return search(...) per branch) O(2^n), high finding O(log n)
merge sort (xs[:mid], xs[mid:]) O(2^n), high finding O(n log n)
quicksort, list-comprehension and in-place partition versions O(2^n), high finding O(n log n)
tree height / size (node.left, node.right; Python, JS, C++ ->) O(2^n), high finding O(n)
BST find (one child per call) O(2^n), high finding O(log n), and the reason states O(n) for an unbalanced tree
fib, tribonacci, Hanoi, grid paths, decode-ways, subset sum O(2^n) / O(3^n) unchanged

Library-call costs had a related problem. A known-cost call anywhere in the function was multiplied by the deepest loop, even when the call was not inside that loop:

code before after
total = sum(xs) then for x in xs: ... O(n²), reason says "sum scans ... inside it" O(n)
ys = sorted(xs) then two nested loops O(n² log n) O(n²)
for (const x of xs.filter(Boolean)) O(n²) O(n), the iterable is evaluated once
for g in groups: out.append(sorted(g)) O(n log n), reason says "sorts inside it" O(n² log n)

The last row is a deliberate change. A linear call inside a loop already scored n × n = n². A sort inside a loop only added a log factor, which disagreed with its own reason text. Now both rules agree: one sort per iteration.

Changes

All in analysis/complexity.py:

  • Self-calls per invocation, not per source text. A call returns through at most one return, so self-calls sitting in different return statements are alternatives. This handles binary search and BST find in every language, because it only uses the IR's RETURN nodes.
  • For ≥ 2 calls per invocation, the arguments decide the label:
    • tree children (.left, ->right, .children …) mean a tree walk, O(n);
    • halving (the existing HALVING pattern: mid, // 2, >> 1 …) means divide and conquer, O(n log n);
    • a parameter stepping by a constant (n - 1, i + 1, s[1:]) means exponential, as before. Requiring a parameter is what keeps in-place quicksort's p - 1 / p + 1 out of this case;
    • anything else is divide and conquer, O(n log n), with lower confidence (0.4) and a reason that names the O(n²) worst case.
  • Divide-and-conquer and tree estimates already include each call's own work, so they are not turned into "O(n · recursion)" when the body also loops (e.g. merge sort with an inline merge loop). The same was already true for O(2^n), and now also holds for O(3^n).
  • Library costs: each known-cost call is multiplied only by the loops of this function that it actually runs inside. Calls in nested functions and loops outside the function no longer count. A call in a for-each loop's header (the iterable) is evaluated once. The result is the larger of the loop nest and the costliest call, and the reason text says which one dominates.
  • Removed the unused COST_ORDER constant.

Testing

  • pytest on Python 3.13, 3.12 and 3.11: 167 passed, 3 skipped. ruff check explain_my_code tests is clean. mypy reports the same 26 errors as before.

  • New parametrised tests in tests/test_analysis.py:

    • test_divide_and_conquer_and_tree_recursion_are_not_exponential (9 cases across Python, JS and C++);
    • test_constant_step_branching_recursion_stays_exponential (5 cases);
    • test_library_costs_only_multiply_the_loops_they_run_inside (6 cases).

    Run against main's source, 13 of these fail, and the 7 that pass are the ones that should already pass. The existing fib, memoised-fib and sort-in-loop tests still pass, and the README's headline fib example gives the same output.

Notes

  • Java is not in the new tests on purpose. While checking this I found that Java calls carry an empty callee, because JavaAdapter._meta_call is never invoked (_COMMON_META binds the base-class function). So Java recursion and library costs can't be classified at all right now: Java fib reads as "part of a recursive cycle through another function". That is a separate adapter fix, coming in its own PR.
  • Still a heuristic. A grid DFS (dfs(r + 1, c) …) with a visited set is still called exponential, as it was before. BST insert written as node.left = insert(...) / node.right = insert(...) reads as O(n), the worst case, because the two calls are in separate if/else arms rather than separate returns.

Generated by Claude Code

…exponential

Any function with two self-calls written down was labelled O(2^n) and got
a high-severity "Exponential recursion" finding telling the reader to
memoise it. That fired on recursive binary search (two calls in separate
returns, one runs), merge sort and quicksort (divide and conquer), and
every binary-tree traversal: most of the recursion people paste.

The estimate now counts self-calls per invocation (calls in different
`return` statements are alternatives) and reads the arguments: tree
children (`node.left`) are a tree walk, halves are divide and conquer,
and only a parameter stepping by a constant (`n - 1`, `s[1:]`) keeps
the exponential label. fib, Hanoi, grid paths and decode-ways stay
O(2^n).

Library costs had the same over-reach: a call anywhere in the function
was multiplied by the deepest loop, so `sum(xs)` before a loop made it
O(n^2). Each call is now multiplied only by the loops it actually runs
inside, a for-each iterable counts as evaluated once, and a sort inside
a loop is a sort per iteration, matching how linear calls were already
treated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW
@ethanzhoucool
ethanzhoucool marked this pull request as ready for review November 3, 2026 17:12
@ethanzhoucool
ethanzhoucool merged commit 0f5e7e8 into main Nov 3, 2026
6 checks passed
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