Created
December 11, 2025 19:04
-
-
Save tatsuyax25/f1227b067177e19900b0f9784ae09568 to your computer and use it in GitHub Desktop.
You are given a positive integer n, representing an n x n city. You are also given a 2D grid buildings, where buildings[i] = [x, y] denotes a unique building located at coordinates [x, y]. A building is covered if there is at least one building in a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number} n | |
| * @param {number[][]} buildings | |
| * @return {number} | |
| */ | |
| var countCoveredBuildings = function(n, buildings) { | |
| // Guard: empty list -> no covered buildings | |
| if (!buildings || buildings.length === 0) return 0; | |
| // Step 1: Precompute extremes per row (y) and column (x). | |
| // minX[y], maxX[y]: smallest and largest x in row y | |
| // minY[x], maxY[x]: smallest and largest y in column x | |
| const minX = new Map(); | |
| const maxX = new Map(); | |
| const minY = new Map(); | |
| const maxY = new Map(); | |
| for (const [x, y] of buildings) { | |
| // Update row extremes | |
| if (!minX.has(y)) { | |
| minX.set(y, x); | |
| maxX.set(y, x); | |
| } else { | |
| minX.set(y, Math.min(minX.get(y), x)); | |
| maxX.set(y, Math.max(maxX.get(y), x)); | |
| } | |
| // Update column extremes | |
| if (!minY.has(x)) { | |
| minY.set(x, y); | |
| maxY.set(x, y); | |
| } else { | |
| minY.set(x, Math.min(minY.get(x), y)); | |
| maxY.set(x, Math.max(maxY.get(x), y)); | |
| } | |
| } | |
| // Step 2: Count buildings that sit strictly between row/column extremes. | |
| let covered = 0; | |
| for (const [x, y] of buildings) { | |
| const rowMin = minX.get(y); | |
| const rowMax = maxX.get(y); | |
| const colMin = minY.get(x); | |
| const colMax = maxY.get(x); | |
| // "Left and right" means x is strictly between rowMin and rowMax. | |
| const hasLeftAndRight = (rowMin < x) && (x < rowMax); | |
| // "Above and below" means y is strictly between colMin and colMax. | |
| const hasAboveAndBelow = (colMin < y) && (y < colMax); | |
| if (hasLeftAndRight && hasAboveAndBelow) { | |
| covered++; | |
| } | |
| } | |
| return covered; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment