Skip to content
Onsite

Count Triplets with Given Sum in Matrix

EasyP3Coding

Look at every run of exactly three adjacent cells in a straight line in matrix: horizontal (left to right), vertical (top to bottom), diagonal down-right, and diagonal down-left (the anti-diagonal direction). Return how many of these runs have values that add up to target.

Each run is counted once, by position. A run is determined by its cells, so the horizontal run [a, b, c] and the same cells read right to left are the same run.

Example 1

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]], target = 6
Output
1

Example 2

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]], target = 15
Output
4

Example 3

Input
matrix = [[1,1,1],[1,1,1],[1,1,1]], target = 3
Output
8

Constraints

  • 1 <= rows, cols <= 100
  • 1 <= matrix[i][j] <= 10^4
  • 1 <= target <= 3 * 10^4
  • All rows have the same length.

Hints

Run checks the 3 visible tests, Submit all 11.