Skip to content

fix: stop convexHullRecursive returning interior points - #7784

Open
Aditya2375 wants to merge 3 commits into
TheAlgorithms:masterfrom
Aditya2375:fix-convex-hull-recursive
Open

Aditya2375 wants to merge 3 commits into
TheAlgorithms:masterfrom
Aditya2375:fix-convex-hull-recursive

Conversation

@Aditya2375

Copy link
Copy Markdown
Contributor

Describe your change:

Fixed ConvexHull.convexHullRecursive returning points that lie strictly inside the convex hull.

The quickhull step picks the "extreme" point (the farthest point from the current line segment, which is guaranteed to be a hull vertex) and recurses on it. But it compared values returned by Point.orientation, which normalizes its result with Integer.compare(..., 0) and therefore only ever returns -1, 0 or 1. Every candidate point compared "equal", so the code simply recursed on the first candidate in list order. An arbitrary point beyond the segment is not guaranteed to be on the hull, so strictly interior points ended up in the result.

Example with the current implementation:

convexHullRecursive([(1,5), (1,8), (2,9), (0,10), (4,19)])
// returns [(1,5), (2,9), (4,19), (1,8), (0,10)]
// (1,8) lies strictly inside the hull of the other four points

The fix computes the actual cross product (as a long, to avoid int overflow) when selecting the extreme point. I also deduplicated the input up front, since coincident input points previously made the < 3 base case return duplicates (e.g. [P, P] -> [P, P]).

I verified the fixed implementation against an independent monotone-chain oracle on 5000 randomized point sets (including collinear and duplicate-heavy inputs): all match. Added regression tests for both cases; both fail on the current code and pass with the fix.

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Java files are placed inside an existing directory.
  • All filenames are in all uppercase characters with no spaces or dashes.
  • 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.
  • If this pull request resolves one or more open issues then the commit message contains Fixes: #{$ISSUE_NO}.

@codecov-commenter

codecov-commenter commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.65%. Comparing base (9e216aa) to head (e6bae2c).
⚠️ Report is 16 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #7784      +/-   ##
============================================
+ Coverage     82.45%   82.65%   +0.20%     
- Complexity     8512     8617     +105     
============================================
  Files           847      848       +1     
  Lines         26291    26461     +170     
  Branches       5134     5179      +45     
============================================
+ Hits          21677    21872     +195     
+ Misses         3825     3809      -16     
+ Partials        789      780       -9     

☔ 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.

@Aditya2375
Aditya2375 marked this pull request as ready for review November 25, 2026 01:21

@DenizAltunkapan DenizAltunkapan 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.

Thanks for fixing the farthest-point selection and adding regressions for interior and duplicate points. I confirmed locally that the recursive hull can still drop a vertex when the cross product overflows. Before merging, please make the arithmetic consistent across the recursive hull and add a regression test for large coordinates.


for (Point p : points) {
int det = Point.orientation(left, right, p);
long det = (long) (right.x() - left.x()) * (p.y() - left.y()) - (long) (right.y() - left.y()) * (p.x() - left.x());

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.

All four coordinate differences are evaluated as int before multiplication, so a cast after subtraction can preserve an already overflowed value. Please widen before subtracting. With unrestricted int coordinates, the determinant can also exceed long. Please use arithmetic that preserves its sign and magnitude across the supported range, or document and enforce a safe coordinate range.

@@ -105,11 +107,11 @@ public static List<Point> convexHullRecursive(List<Point> points) {
private static void constructHull(Collection<Point> points, Point left, Point right, Set<Point> convexSet) {

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.

The initial upper/lower split and the final angle sort and collinearity filter still call Point.orientation(), which computes the cross product entirely in int. Please use the same overflow-safe orientation throughout the recursive hull. The squared-distance tie-breaker in the angle sort also needs to respect the supported coordinate range.

assertTrue(isCounterClockwise(resultCollinear), "The result of the collinear test should be in counter-clockwise order");
}
@Test
void testConvexHullRecursiveExcludesInteriorPoints() {

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.

Please add a regression with large positive and negative coordinates. I compiled this revision and checked the triangle (-32768, -32768), (32768, -32768), (-32768, 32768). The initial split treats the three points as collinear after the cross product wraps to zero, and the result drops (32768, -32768).

Compute the cross product exactly (differences widened to long, BigInteger for the product) in the brute force check, the initial split, constructHull and the angle sort. Drop the collinear tie-break and filter in sortCounterClockwise, which cannot trigger because hull vertices are strictly convex. Add tests with large coordinates.
@Aditya2375

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. Pushed e6bae2c: the cross product is now computed exactly everywhere in ConvexHull (brute force check, initial split, constructHull, angle sort), with the differences widened to long first and BigInteger for the product, so it holds over the full int range. I removed the collinear tie-break in the angle sort since hull vertices are strictly convex and it can't be reached, which also removes the squared distance question. Added tests for your (-32768, -32768), (32768, -32768), (-32768, 32768) triangle and for points at Integer.MIN_VALUE / MAX_VALUE.

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