Skip to content

fix(misc): prevent overflow when averaging the two middle values of a running median - #7781

Merged
alxkm merged 2 commits into
TheAlgorithms:masterfrom
shreyanshj10:fix-median-overflow
Nov 24, 2026
Merged

alxkm merged 2 commits into
TheAlgorithms:masterfrom
shreyanshj10:fix-median-overflow

Conversation

@shreyanshj10

Copy link
Copy Markdown
Contributor

MedianOfRunningArray returns calculateAverage(maxHeap.peek(), minHeap.peek()) whenever the
stream holds an even number of values, and two of the six subclasses compute that average as
(a + b) / 2. The sum overflows once the two middle values are large, so the median comes back
wrong with no error:

  • MedianOfRunningArrayInteger: insert Integer.MAX_VALUE and then Integer.MAX_VALUE - 2, and
    getMedian() returns -2 instead of 2147483646. Near Integer.MIN_VALUE it returns 1
    instead of -2147483647.
  • MedianOfRunningArrayLong fails the same way near Long.MAX_VALUE and Long.MIN_VALUE.

For the Integer subclass I sum into a long before halving. For the Long subclass there is no
wider primitive, so I sum into a BigInteger; BigInteger.divide truncates toward zero, which is
what the existing behaviour does, so negative medians are unchanged (testWithNegativeValues
still asserts that the median of -1 and -2 is -1). I checked that against the old expression
over every int and long pair in [-200, 200], two million random long pairs and the values at
both ends of each range: the new code agrees everywhere the old code did not overflow, and matches
the exact midpoint everywhere else.

I left the Byte subclass alone because it cannot overflow: its operands promote to int and the
average of two bytes is always back in range. The Float and Double subclasses do have a related
problem -- the sum reaches Infinity for values near MAX_VALUE -- but the obvious a / 2 + b / 2
rewrite returns 0.0 for two subnormals, so that one needs more thought than this fix and I would
rather keep it separate.

The four new tests in MedianOfRunningArrayTest fail on the current code with the values above and
pass with this change. The other 17 tests in that class are untouched and still pass.

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized it.
  • All filenames are in PascalCase.
  • All functions and variable names follow Java naming conventions.
  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. -- not applicable, no new algorithm
  • All new algorithms include a corresponding test class that validates their functionality. -- not applicable, the tests go in the existing MedianOfRunningArrayTest
  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

MedianOfRunningArrayInteger and MedianOfRunningArrayLong both compute
(a + b) / 2, which overflows once the two middle values of the stream
are large. For an Integer stream holding Integer.MAX_VALUE and
Integer.MAX_VALUE - 2 the median came back as -2 instead of
2147483646; the Long version fails the same way near Long.MAX_VALUE.

Sum in a long for the Integer case, and in a BigInteger for the Long
case since there is no wider primitive. Add regression tests for both
types at each end of their range.
@codecov-commenter

codecov-commenter commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.45%. Comparing base (c86ec0a) to head (2cedfc8).

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #7781   +/-   ##
=========================================
  Coverage     82.45%   82.45%           
+ Complexity     8515     8514    -1     
=========================================
  Files           847      847           
  Lines         26292    26293    +1     
  Branches       5134     5134           
=========================================
+ Hits          21680    21681    +1     
  Misses         3824     3824           
  Partials        788      788           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@alxkm alxkm left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Thank you for the contribution.

@alxkm
alxkm merged commit 15a4a9d into TheAlgorithms:master Nov 24, 2026
7 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.

3 participants