Skip to main content

Difference of Number of Distinct Values on Diagonals - Solution & Explanation

MediumArrayHash TableMatrix18 min read
Practice this problem

Problem Statement

Given a 2D grid of size m x n, you should find the matrix answer of size m x n.

The cell answer[r][c] is calculated by looking at the diagonal values of the cell grid[r][c]:

  • Let leftAbove[r][c] be the number of distinct values on the diagonal to the left and above the cell grid[r][c] not including the cell grid[r][c] itself.
  • Let rightBelow[r][c] be the number of distinct values on the diagonal to the right and below the cell grid[r][c], not including the cell grid[r][c] itself.
  • Then answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|.

A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.

  • For example, in the below diagram the diagonal is highlighted using the cell with indices (2, 3) colored gray:
    • Red-colored cells are left and above the cell.
    • Blue-colored cells are right and below the cell.

Return the matrix answer.

 

Example 1:

Input: grid = [[1,2,3],[3,1,5],[3,2,1]]

Output: Output: [[1,1,0],[1,0,1],[0,1,1]]

Explanation:

To calculate the answer cells:

answer left-above elements leftAbove right-below elements rightBelow |leftAbove - rightBelow|
[0][0] [] 0 [grid[1][1], grid[2][2]] |{1, 1}| = 1 1
[0][1] [] 0 [grid[1][2]] |{5}| = 1 1
[0][2] [] 0 [] 0 0
[1][0] [] 0 [grid[2][1]] |{2}| = 1 1
[1][1] [grid[0][0]] |{1}| = 1 [grid[2][2]] |{1}| = 1 0
[1][2] [grid[0][1]] |{2}| = 1 [] 0 1
[2][0] [] 0 [] 0 0
[2][1] [grid[1][0]] |{3}| = 1 [] 0 1
[2][2] [grid[0][0], grid[1][1]] |{1, 1}| = 1 [] 0 1

Example 2:

Input: grid = [[1]]

Output: Output: [[0]]

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n, grid[i][j] <= 50

Approach Overview

Problem Overview: You are given an m x n grid. For every cell (i, j), compute the absolute difference between the number of distinct values on the top-left diagonal before that cell and the number of distinct values on the bottom-right diagonal after it. The result is stored in a matrix of the same size.

Approach 1: Diagonal Traversal with Precomputation (O(m*n) time, O(m*n) space)

Each cell belongs to exactly one top-left → bottom-right diagonal. Traverse every diagonal and compute two pieces of information: the count of distinct values seen before each position and the count of distinct values after it. Use a hash set while walking the diagonal from top-left to bottom-right to track distinct values encountered so far, storing prefix counts. Then walk the same diagonal in reverse to collect suffix distinct counts. The result for each cell is abs(prefixDistinct - suffixDistinct). This approach processes each element a constant number of times, giving O(m*n) time. Extra arrays for prefix/suffix information lead to O(m*n) space.

Diagonal traversal is a common pattern in matrix problems where elements share structural relationships. Using a hash table or set ensures distinct checks remain O(1) on average.

Approach 2: Simultaneous Diagonal Pass Method (O(m*n) time, O(min(m,n)) space)

Instead of storing prefix and suffix arrays, process each diagonal in a single controlled pass using two hash sets. Move along the diagonal and maintain a set of values already seen (top-left side). Before updating it, compute the number of distinct values remaining on the bottom-right side by maintaining another set or pre-counted structure. As you advance, shift elements from the future set to the past set and update the answer in place. Because each diagonal length is at most min(m, n), the auxiliary memory remains bounded by the diagonal size rather than the whole matrix.

This method keeps the same O(m*n) runtime but reduces auxiliary memory usage. It relies heavily on fast set operations and careful ordering of updates while iterating along the diagonal.

Problems like this combine array traversal with diagonal indexing tricks. The key insight: treat each diagonal independently instead of recalculating distinct counts from every cell.

Recommended for interviews: The diagonal traversal with precomputation approach is the safest explanation during interviews. It clearly demonstrates how you decompose the matrix into diagonals and track distinct values using hash sets. Once the interviewer sees the O(m*n) logic, mentioning the simultaneous-pass optimization shows deeper understanding of space tradeoffs.

Approach 1: Diagonal Traversal with Precomputation

This approach involves precomputing diagonal elements so that when we calculate distinct values for each diagonal, we can directly access those precomputed results instead of recalculating them from scratch for every cell.

The C implementation uses a naive diagonal traversal method, maintaining sets of diagonals and calculating distinct values of these diagonals in advance. This allows us to access distinct counts efficiently.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(m * n), where m and n are dimensions of the grid.
Space Complexity: O(m * n), for storing leftAbove and rightBelow counts.

Try this approach in the editor →

Approach 2: Simultaneous Diagonal Pass Method

This strategy employs a simultaneous diagonal pass from both directions using a two-pointer strategy to dynamically compute and update diagonal distinct values while traversing the grid matrix.

Utilizing two directions with usage of an array to calculate and maintain the current distinct element count, the C solution uses manual memory management to balance complexity.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(m * n) - Each diagonal value is set once per element.
Space Complexity: O(max(m, n)) - Due to diagonal operational arrays.

Try this approach in the editor →

Approach 3: Simulation

We can simulate the process described in the problem statement, calculating the number of distinct values on the top-left diagonal tl and the bottom-right diagonal br for each cell, then compute their difference |tl - br|.

The time complexity is O(m times n times min(m, n)), and the space complexity is O(m times n).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Diagonal Traversal with Precomputation

Time Complexity: O(m * n), where m and n are dimensions of the grid.
Space Complexity: O(m * n), for storing leftAbove and rightBelow counts.

Simultaneous Diagonal Pass Method

Time Complexity: O(m * n) - Each diagonal value is set once per element.
Space Complexity: O(max(m, n)) - Due to diagonal operational arrays.

Simulation

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Diagonal Traversal with PrecomputationO(m*n)O(m*n)Best for clarity and interviews; easy to reason about prefix and suffix distinct counts per diagonal
Simultaneous Diagonal Pass MethodO(m*n)O(min(m,n))When memory usage matters and you want to avoid storing extra matrices

Video Solution

6440. Difference of Number of Distinct Values on Diagonals | Leetcode Weekly Contest 347| Solution.Optimization868 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Difference of Number of Distinct Values on Diagonals easy or hard?
The problem is generally classified as Medium difficulty. The challenge is recognizing that each cell's computation depends only on its diagonal and avoiding repeated scans. Once the diagonal traversal pattern is identified, the solution becomes a straightforward hash set application.
Difference of Number of Distinct Values on Diagonals Python/Java solution
Implementations typically iterate through each diagonal and maintain sets for values seen before and after a cell. Languages like Python use the built-in set, while Java and C++ use HashSet or unordered_set. The algorithm structure remains the same and runs in O(m*n) time.
How to solve Difference of Number of Distinct Values on Diagonals in O(m*n)?
Iterate through every diagonal of the matrix. Maintain a set of values seen before each position and compute distinct counts on the remaining part of the diagonal. Store the absolute difference between these counts for each cell. Because each element belongs to one diagonal and is processed only a few times, the runtime stays O(m*n).
What is the best approach for Difference of Number of Distinct Values on Diagonals?
The most reliable approach is diagonal traversal with prefix and suffix distinct counts. Treat each top-left to bottom-right diagonal independently, track values with a hash set, and compute the absolute difference for each cell. This method runs in O(m*n) time and is straightforward to implement in most languages.
Is Difference of Number of Distinct Values on Diagonals asked at Google/Amazon/Meta?
Matrix traversal and diagonal-processing problems frequently appear in technical interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, the underlying skills—hash sets, matrix indexing, and diagonal traversal—are common interview patterns.
What data structure is used in Difference of Number of Distinct Values on Diagonals?
The primary data structure is a hash set (or hash table) used to track distinct values along a diagonal. It provides O(1) average-time insert and lookup operations, which keeps the overall algorithm linear with respect to the matrix size.
What is the time complexity of Difference of Number of Distinct Values on Diagonals?
The optimal solutions run in O(m*n) time, where m and n are the grid dimensions. Each element is processed a constant number of times while traversing diagonals. Hash set operations for inserting and checking distinct values take O(1) average time.

Ready to solve this problem?

Practice Difference of Number of Distinct Values on Diagonals with our built-in code editor and test cases.

Practice on FleetCode