#3567
Minimum Absolute Difference in Sliding Submatrix
MediumArraySortingMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n * k²) | O(m * n * log(k²)) |
| Space | O(k²) | O(k²) |
💡
Intuition
Time O(m * n * log(k²))Space O(k²)
Using a sliding window approach with a sorted data structure allows us to maintain the values in the current k x k submatrix efficiently, enabling quick calculation of the minimum absolute difference.
⚙️
Algorithm
3 steps- 1Step 1: Use a sorted list to maintain values in the current k x k submatrix.
- 2Step 2: As the window slides, add new values and remove old values while keeping the list sorted.
- 3Step 3: Calculate the minimum absolute difference from the sorted list in constant time.
solution.py21 lines
1from sortedcontainers import SortedList
2
3def minAbsDiffSubmatrix(grid, k):
4 m, n = len(grid), len(grid[0])
5 ans = [[0] * (n - k + 1) for _ in range(m - k + 1)]
6 for i in range(m - k + 1):
7 current = SortedList()
8 for j in range(n - k + 1):
9 if j == 0:
10 for x in range(k):
11 for y in range(k):
12 current.add(grid[i + x][j + y])
13 else:
14 for x in range(k):
15 current.remove(grid[i + x][j - 1])
16 current.add(grid[i + x][j + k - 1])
17 min_diff = float('inf')
18 for a in range(len(current) - 1):
19 min_diff = min(min_diff, current[a + 1] - current[a])
20 ans[i][j] = min_diff
21 return ansℹ
Complexity note: We maintain a sorted list of values in the current window, allowing efficient insertions and deletions, leading to logarithmic complexity for updates.
- 1Using sorted data structures can optimize minimum difference calculations.
- 2Sliding window techniques reduce redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.