Frontend School

Count Safe Pins

DSA
easy

Count Safe Pins

Easy
Matrix
Arrays

Overview

At Pinterest, maintaining a healthy and safe content ecosystem is paramount. Boards are curated collections of pins, and sometimes, certain pins might be flagged due to content policy violations. These flagged pins can potentially compromise other nearby pins, requiring a careful moderation process. This problem asks you to simulate a simplified content scan to identify and count 'safe' pins.

What you need to do / Task

Implement a function countSafePins that takes a 2D integer matrix, board, representing a Pinterest board. Your task is to count the total number of 'safe' pins on this board.

A pin is defined as follows:

  • A cell with value 1 represents a regular pin.
  • A cell with value 0 represents an empty space.
  • A cell with value -1 represents a flagged (problematic) pin.

A regular pin (1) is considered compromised if it is directly adjacent (horizontally or vertically, not diagonally) to any flagged pin (-1). A regular pin is considered safe if it is not compromised.

Input & output

  • Input: board (number[][]) - A 2D array of integers representing the Pinterest board. Each element board[r][c] will be 0, 1, or -1.
  • Output: number - The total count of safe pins on the board.

Clarifications

  • Adjacency: Only direct horizontal and vertical neighbors (up, down, left, right) should be considered. Diagonal cells are not adjacent.
  • Board Boundaries: Cells outside the board's dimensions are not considered pins and thus cannot be flagged or regular pins.

Examples

1

Example 1

Input:

board = [[1, 1, 1], [1, -1, 1], [1, 1, 1]]

Output:

4

Note:

The flagged pin at (1,1) compromises its direct neighbors: (0,1), (1,0), (1,2), and (2,1). The pins at (0,0), (0,2), (2,0), and (2,2) are regular pins not adjacent to any flagged pin, hence they are safe.

2

Example 2

Input:

board = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]

Output:

4

Note:

There are no flagged pins (-1) on the board. Therefore, all regular pins (1) at (0,0), (0,2), (2,0), and (2,2) are considered safe.

3

Example 3

Input:

board = [[-1, 1], [1, 1]]

Output:

1

Note:

The flagged pin at (0,0) compromises its direct neighbors: (0,1) and (1,0). The pin at (1,1) is a regular pin and is not adjacent to the flagged pin (0,0) (it's diagonal), so it is safe.

Constraints

Constraints & assumptions

  • 1 <= board.length <= 100
  • 1 <= board[0].length <= 100
  • board[r][c] will be 0, 1, or -1.

What interviewers evaluate

  • Ability to correctly iterate through a 2D matrix and perform neighbor checks.
  • Correct handling of boundary conditions for neighbor access.
  • Accurate logic for determining if a pin is 'safe' or 'compromised'.
  • Efficiency of the solution in terms of time and space complexity.

Loading editor...