💡 All diagonals have been sorted and replaced in the matrix.
from typing import List
import collections
import heapq
def diagonalSort(mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0]) # STEP 1
diagonals = collections.defaultdict(list) # STEP 1
# Build min-heaps for each diagonal
for i in range(m): # STEP 2-13
for j in range(n):
heapq.heappush(diagonals[i - j], mat[i][j]) # STEP 2-13
# Replace elements by polling from heaps
for i in range(m): # STEP 14-25
for j in range(n):
mat[i][j] = heapq.heappop(diagonals[i - j]) # STEP 14-25
return mat
# Driver code
if __name__ == '__main__':
matrix = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
print(diagonalSort(matrix))
📊
Sort Matrix Diagonally - Watch the Algorithm Execute, Step by Step
Watching each step of the extraction, sorting, and reinsertion makes it clear how the algorithm handles diagonals independently and why this approach is efficient.
✓ Each diagonal is identified by the key (row - column) and processed independently.
This insight is hard to see from code alone because the diagonal key calculation is subtle and not explicitly visualized.
✓ Using min-heaps for each diagonal allows efficient sorting and retrieval of the smallest elements.
Watching heaps fill and then pop elements clarifies how sorting is done without sorting the entire matrix.
✓ The two-pass traversal first builds heaps, then replaces matrix elements, ensuring diagonals are sorted in-place.
Seeing the pointer movements and heap operations step-by-step reveals the algorithm's structure and flow.
Practice
(1/5)
1. Given the following code for computing the h-index, what is the returned value when the input is [4, 1, 0, 5, 6]?
easy
A. 3
B. 4
C. 5
D. 2
Solution
Step 1: Sort citations descending
Sorted list: [6,5,4,1,0]
Step 2: Binary search on h from 0 to 5
Check mid=2: count papers >=2 is 3 (6,5,4) ≥2 -> low=3; mid=4: count ≥4 is 3 -> low=5; mid=5: count ≥5 is 2 -> high=4; loop ends with high=4.
Final Answer:
Option B -> Option B
Quick Check:
Final h-index is 4 for this input [OK]
Hint: Count papers ≥ mid after sorting [OK]
Common Mistakes:
Off-by-one in binary search boundaries
Not breaking early in count loop
Returning low instead of high
2. Consider the following Python code for finding the maximum gap in a list of integers. What is the value of max_gap after the second iteration of the for-loop when the input is [3, 6, 9, 1]?
from typing import List
def maximumGap(nums: List[int]) -> int:
if len(nums) < 2:
return 0
min_num, max_num = min(nums), max(nums)
if min_num == max_num:
return 0
nums.sort()
max_gap = 0
for i in range(1, len(nums)):
max_gap = max(max_gap, nums[i] - nums[i-1])
return max_gap
print(maximumGap([3,6,9,1])) # Output: ?
Hint: Sort first, then scan adjacent differences [OK]
Common Mistakes:
Off-by-one errors in loop
Using unsorted array differences
Confusing iteration indices
3. You are given a sorted list of unique integers and a range defined by lower and upper. You need to find all the missing continuous ranges within this interval that are not present in the list. Which algorithmic approach best guarantees an optimal solution in terms of time complexity?
easy
A. Sorting the list and then scanning linearly to find gaps
B. Using binary search to quickly locate missing ranges between elements
C. Dynamic programming to build missing ranges from subproblems
D. Greedy approach scanning the entire range and adding missing numbers one by one
Solution
Step 1: Understand problem constraints
The problem requires finding missing ranges efficiently within a sorted list and a given interval.
Step 2: Identify approach that leverages sorted data
Since the list is already sorted, scanning linearly to find gaps between consecutive elements is optimal and straightforward.
Step 3: Evaluate binary search approach
Using binary search to locate missing ranges is unnecessary overhead because the list is sorted and unique; a linear scan suffices.
Final Answer:
Option A -> Option A
Quick Check:
Linear scan over sorted unique list is O(n), optimal for this problem [OK]
Hint: Linear scan over sorted unique list is optimal for missing ranges [OK]
Common Mistakes:
Assuming binary search is needed despite sorted input
Confusing DP with range search
Ignoring linear scan benefits
4. Consider the following Python code implementing the optimal approach for relative sorting. Given arr1 = [3,1,2,2] and arr2 = [2,3], what is the final returned list?