| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const saddlePoints = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const saddlePoints = (grid) => { |
| 7 | // Edge Case: Empty grid |
| 8 | if (!grid || grid.length === 0) { |
| 9 | return []; |
| 10 | } |
| 11 | |
| 12 | // Edge Case: Grid with empty rows |
| 13 | if (grid[0].length === 0) { |
| 14 | return []; |
| 15 | } |
| 16 | |
| 17 | const numRows = grid.length; |
| 18 | const numCols = grid[0].length; |
| 19 | const saddlePoints = []; |
| 20 | |
| 21 | // Precompute row maxima |
| 22 | const rowMax = new Array(numRows).fill(0); |
| 23 | for (let i = 0; i < numRows; i++) { |
| 24 | rowMax[i] = Math.max(...grid[i]); |
| 25 | } |
| 26 | |
| 27 | // Precompute column minima |
| 28 | const colMin = new Array(numCols).fill(0); |
| 29 | for (let j = 0; j < numCols; j++) { |
| 30 | const column = grid.map(row => row[j]); |
| 31 | colMin[j] = Math.min(...column); |
| 32 | } |
| 33 | |
| 34 | // Find saddle points |
| 35 | for (let i = 0; i < numRows; i++) { |
| 36 | for (let j = 0; j < numCols; j++) { |
| 37 | const value = grid[i][j]; |
| 38 | if (value === rowMax[i] && value === colMin[j]) { |
| 39 | saddlePoints.push({ row: i + 1, column: j + 1 }); |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | return saddlePoints; |
| 8 | 45 | }; |
| 46 | // Handled Edge Cases: empty grid, grid with empty rows |