LeetCode in Kotlin

3531. Count Covered Buildings

Medium

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 all four directions: left, right, above, and below.

Return the number of covered buildings.

Example 1:

Input: n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]

Output: 1

Explanation:

Example 2:

Input: n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]

Output: 0

Explanation:

Example 3:

Input: n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]

Output: 1

Explanation:

Constraints:

Solution

import kotlin.math.max
import kotlin.math.min

class Solution {
    private fun helper(buildings: Array<IntArray>, n: Int): Int {
        val minRow = IntArray(n + 1)
        val maxRow = IntArray(n + 1)
        val minCol = IntArray(n + 1)
        val maxCol = IntArray(n + 1)
        minRow.fill(n + 1)
        minCol.fill(n + 1)
        for (b in buildings) {
            val x = b[0]
            val y = b[1]
            minRow[x] = min(minRow[x], y)
            maxRow[x] = max(maxRow[x], y)
            minCol[y] = min(minCol[y], x)
            maxCol[y] = max(maxCol[y], x)
        }
        var ans = 0
        for (arr in buildings) {
            val x = arr[0]
            val y = arr[1]
            if (minRow[x] < y && maxRow[x] > y && minCol[y] < x && maxCol[y] > x) {
                ans++
            }
        }
        return ans
    }

    fun countCoveredBuildings(n: Int, buildings: Array<IntArray>): Int {
        return helper(buildings, n)
    }
}