↓Skip to main content
  1. LeetCode/

LeetCode 1030: Matrix Cells in Distance Order

·2 mins· ·
LeetCode Easy Array Math Geometry Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-30

  • Submissions: Runtime Error ×2 → Wrong Answer ×5 → Accepted ×3 → Runtime Error → Accepted

Approach
#

There are at most 100 × 100 cells, so list the coordinates and sort by abs(i - r0) + abs(j - c0). Distances are at most rows + cols, so a counting sort or a BFS from the center gives O(rows × cols) (Bucket Sort).

My Attempts
#

This took 12 submissions, mainly returning distances instead of coordinates: each cell became [|r0 - i|, |c0 - j|] before sorting, and the key went through len (always 2, so no sorting) and sum with reverse=True (backwards). Sorting the coordinates themselves with the distance as key passed.

Solution
#

class Solution:
    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
        cells = [[i, j] for i in range(rows) for j in range(cols)]
        cells.sort(key=lambda p: abs(p[0] - rCenter) + abs(p[1] - cCenter))
        return cells

Complexity
#

Time O(RC log(RC)), space O(RC).

Mistakes to Avoid
#

  • Return coordinates; the distance is only the sort key.
  • The distance is the sum of absolute differences, not key=len or key=sum.

Interview Explanation
#

I list all coordinates and sort by Manhattan distance to the center; with at most ten thousand cells sorting is fast enough, and counting sort or BFS from the center would be linear.

Related

LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left
LeetCode 883: Projection Area of 3D Shapes
·1 min
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 note: the top view counts nonzero cells, and the front and side views sum each row’s and each column’s maximum
LeetCode 812: Largest Triangle Area
·2 mins
LeetCode Easy Array Math Geometry Polygons
LeetCode 812 note: with at most 50 points, enumerate every triple and take the largest shoelace area
LeetCode 628: Maximum Product of Three Numbers
·1 min
LeetCode Easy Array Math Sorting
LeetCode 628 note: after sorting there are only two candidates: the three largest, or the two smallest (negatives) times the largest
LeetCode 1005: Maximize Sum Of Array After K Negations
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 1005 note: negate the smallest value each time; once the smallest is positive, only the parity of the remaining count matters
LeetCode 977: Squares of a Sorted Array
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 977 note: the largest squares are at the two ends, so compare the ends with two pointers and fill the result from the back