Goldman Sachs OA Interview Question: Counting Connections in a Matrix

21 Views
No Comments

Given a matrix of size m x n, m denotes the row starting with index 0 and n denotes the column starting with index 0.

The elements in the matrix are populated with values either 1 or 0. 1 indicates the matrix position is available for establishing the connection and 0 indicates the matrix position is not available for establishing the connection.

We need to connect the available adjacent positions vertically, horizontally, and diagonally and count the number of distinct connections established.

For example, given a matrix of size 3 x 4, the elements are stored as follows:

1 0 0 1
0 1 1 1
1 0 0 1

The expected output is 8.

In the above example, the positions are connected as follows and hence 8 connections are possible:

  • (0,0) -> (1,1)
  • (2,0) -> (1,1)
  • (1,1) -> (1,2)
  • (1,2) -> (0,3)
  • (1,2) -> (1,3)
  • (1,2) -> (2,3)
  • (0,3) -> (1,3)
  • (1,3) -> (2,3)

Input:

  • m – integer – number of rows
  • n – integer – number of columns
  • m * n matrix

This Goldman Sachs OA problem asks you to count how many connections can be formed between adjacent cells with value 1 in a matrix. Adjacency includes horizontal, vertical, and diagonal neighbors, so each cell has up to 8 neighboring directions. A clean solution is to scan the grid, check all valid neighbors for every 1, and make sure each connection is counted only once, typically by dividing the final count by 2 or by counting only in fixed directions.

END
 0