Find Maximum Area of a Triangle - Problem

You are given a 2D array coords of size n x 2, representing the coordinates of n points in an infinite Cartesian plane.

Find twice the maximum area of a triangle with its corners at any three elements from coords, such that at least one side of this triangle is parallel to the x-axis or y-axis.

Formally, if the maximum area of such a triangle is A, return 2 * A. If no such triangle exists, return -1.

Note that a triangle cannot have zero area.

Input & Output

Example 1 — Basic Triangle
$ Input: coords = [[1,3],[5,3],[3,5]]
Output: 8
💡 Note: Points (1,3) and (5,3) form a horizontal side of length 4. The third point (3,5) is at distance 2 from this horizontal line. Area = 4 × 2 / 2 = 4. Return 2 × 4 = 8.
Example 2 — Vertical Side
$ Input: coords = [[2,1],[2,4],[6,2]]
Output: 12
💡 Note: Points (2,1) and (2,4) form a vertical side of length 3. The third point (6,2) is at distance 4 from this vertical line. Area = 3 × 4 / 2 = 6. Return 2 × 6 = 12.
Example 3 — No Valid Triangle
$ Input: coords = [[1,1],[2,3],[4,5]]
Output: -1
💡 Note: No two points share the same x or y coordinate, so no triangle can have an axis-parallel side. Return -1.

Constraints

  • 3 ≤ coords.length ≤ 1000
  • -109 ≤ coords[i][0], coords[i][1] ≤ 109
  • All coordinate pairs are unique

Visualization

Tap to expand
Find Maximum Area of a Triangle Hash Map Optimization Approach INPUT x y (1,3) (5,3) (3,5) coords array: [[1,3], [5,3], [3,5]] 1 3 5 3 5 n = 3 points ALGORITHM STEPS 1 Build Hash Maps Group points by x and y coords xMap: {1:[3], 3:[5], 5:[3]} yMap: {3:[1,5], 5:[3]} 2 Find Parallel Sides Points with same y form base y=3: points (1,3),(5,3) 3 Calculate Height Max vertical distance to apex base = |5-1| = 4 height = |5-3| = 2 4 Compute 2*Area 2A = base * height 2A = 4 * 2 = 8 FINAL RESULT (1,3) (5,3) (3,5) base=4 h=2 Output: 8 2 * Area = 2 * 4 = 8 Area = (4 * 2) / 2 = 4 OK - Valid Triangle Key Insight: For a triangle with one side parallel to an axis, we need two points sharing the same x OR y coordinate. Using hash maps to group points by coordinates allows O(n^2) complexity instead of brute force O(n^3). Formula: 2*Area = base * height (avoiding division gives integer result). TutorialsPoint - Find Maximum Area of a Triangle | Hash Map Optimization
Asked in
Google 25 Amazon 18 Microsoft 15
12.4K Views
Medium Frequency
~25 min Avg. Time
286 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen