You are given a 2D array where each element is an array [length, width] representing the dimensions of a rectangle. You need to calculate the length of the diagonal for each rectangle. Your goal is to find the rectangle that has the strictly longest diagonal. If there is a tie (multiple rectangles have the exact same longest diagonal), you must return the maximum area among those tied rectangles.
This is an entry-level Array Traversal and Math problem. It tests basic geometric formulas (Pythagorean theorem) and multi-variable state tracking. Interviewers use it as a warm-up to ensure candidates can write conditional logic that handles tie-breakers without writing messy, convoluted if-else trees.
This problem follows a simple Linear Scan (Single Pass) pattern. You iterate through the list of rectangles, maintaining two global tracking variables: max_diagonal and max_area_of_longest_diagonal. For each rectangle, calculate its diagonal squared ().
max_diagonal, update max_diagonal and completely overwrite max_area with the current rectangle's area.max_diagonal, you update max_area to be the max(max_area, current_area).Rectangles: [[9, 3], [8, 6]]
[9, 3].
max_diag = 90, max_area = 27.[8, 6].
max_diag = 100, max_area = 48.
Return 48.If another rectangle had diag = 100 but area = 50, the equality condition would trigger and max_area would bump up to 50.
A common mistake is using Math.sqrt() to calculate the exact diagonal length. Floating-point square roots suffer from precision loss. If two diagonals are extremely close in value, a float might evaluate them as equal when they aren't. Because the square root function is strictly increasing, implies . Therefore, you should always compare the squared diagonal lengths () using exact integers to ensure 100% accuracy and faster computation.
When an interview question involves geometric distances, distances between points, or diagonals, avoid Math.sqrt unless the prompt explicitly asks for a float return type. Comparing squared distances using integers is an industry-standard optimization that shows the interviewer you care about both performance and type safety.