Problem 764

Abstract / Summary

Find the largest plus sign of 1s in a grid and return its size.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0764.py

class Solution:
    def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
        allx = defaultdict(list)
        ally = defaultdict(list)
        for m in mines:
            allx[m[0]].append(m[1])
            ally[m[1]].append(m[0])

        for a in allx:
            allx[a].sort()
        for a in ally:
            ally[a].sort()

        result = 0
        for x in range(n):
            for y in range(n):
                left  = -1
                right = n
                pos = bisect_left(ally[y], x)
                if pos < len(ally[y]):
                    right = ally[y][pos]
                if pos > 0:
                    left  = ally[y][pos - 1]

                if right == x or left == x:
                    continue

                gapx = min(abs(x - right), abs(x - left))

                top    = -1
                bottom = n
                pos = bisect_left(allx[x], y)
                if pos < len(allx[x]):
                    bottom = allx[x][pos]
                if pos > 0:
                    top    = allx[x][pos - 1]

                if top == y or bottom == y:
                    continue

                gapy = min(abs(y - top), abs(y - bottom))

                size   = min(gapx, gapy)
                result = max(result, size)

        return result
46 lines | 1363 bytes | submitted September 21, 2023 | GitHub   tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The routine determines the maximum order of a plus sign that can be placed on an n × n grid containing forbidden cells (mines). A plus sign of order k consists of a central cell and four arms extending k - 1 cells in the up, down, left, and right directions, all of which must be free of mines. The algorithm examines every grid position as a potential centre, computes the longest clear stretch in each cardinal direction, and keeps the greatest feasible order found.

Data Preparation

Two hash maps are created: one groups mine column indices by row (allx), the other groups mine row indices by column (ally). Each mine coordinate [r, c] is appended to the appropriate list, after which every list is sorted to enable binary search.

allx = defaultdict(list)
ally = defaultdict(list)
for m in mines:
    allx[m[0]].append(m[1])
    ally[m[1]].append(m[0])

for a in allx:
    allx[a].sort()
for a in ally:
    ally[a].sort()

Sorting once up front allows rapid location of the nearest mine on any row or column during the main scan.

Scanning Cells

The algorithm iterates over every possible centre (x, y) using two nested loops ranging from 0 to n-1. For each cell it attempts to locate the closest mines to the left, right, top, and bottom.

result = 0
for x in range(n):
    for y in range(n):
        ...

Determining Horizontal Extent

For the current column y, the list ally[y] holds the rows of mines in that column. A binary search (bisect_left) finds the insertion point of x. The element at that position, if it exists, is the first mine below the centre (right). The element just before the insertion point, if any, is the nearest mine above (left). If the centre itself coincides with a mine, the iteration skips further processing.

left  = -1
right = n
pos = bisect_left(ally[y], x)
if pos < len(ally[y]):
    right = ally[y][pos]
if pos > 0:
    left  = ally[y][pos - 1]

if right == x or left == x:
    continue

The horizontal clearance gapx is the smaller distance from the centre to the nearest mine on either side.

gapx = min(abs(x - right), abs(x - left))

Determining Vertical Extent

A symmetric procedure examines the row x. The list allx[x] contains the columns of mines in that row. Binary search yields the nearest mines to the right (bottom) and left (top). The centre is discarded if it is a mine.

top    = -1
bottom = n
pos = bisect_left(allx[x], y)
if pos < len(allx[x]):
    bottom = allx[x][pos]
if pos > 0:
    top    = allx[x][pos - 1]

if top == y or bottom == y:
    continue

The vertical clearance gapy is the smaller distance to the nearest mine above or below.

gapy = min(abs(y - top), abs(y - bottom))

Computing Plus Size

The feasible order for the current centre is the minimum of the horizontal and vertical clearances, because a plus sign cannot extend farther than the shortest arm. The global maximum result is updated whenever a larger order is discovered.

size   = min(gapx, gapy)
result = max(result, size)

After all cells have been examined, result holds the order of the largest possible plus sign and is returned.

return result

Edge Cases Handled

When a row or column contains no mines, the corresponding list is empty; the binary search then yields a position of 0, leaving left as -1 and right as n. Consequently, the distance to the grid border is used as the clearance, allowing a plus sign to reach the edge of the board. The explicit checks if right == x or left == x and if top == y or bottom == y ensure that cells occupied by mines are never considered as centres. The use of sentinel values -1 and n guarantees correct distance calculations even at the outermost rows and columns.

Performance Optimizations

The code leverages defaultdict to avoid explicit existence checks when populating the mine maps. Sorting each row and column list a single time enables subsequent binary searches, which run in logarithmic time relative to the number of mines in that line. By locating the nearest mines with bisect_left, the algorithm avoids scanning entire rows or columns for each centre. Early continue statements discard centres that are mines or that have zero clearance in either direction, preventing unnecessary calculations for those positions. The use of simple arithmetic (min, abs) to compute clearances keeps the inner loop lightweight, allowing the double-loop over the grid to remain the dominant work without extra overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a giant square grid of squares like a big sheet of graph paper. Some of those squares have little landmines buried inside them that we need to avoid. The goal is to find the biggest cross shape we can draw made of empty squares. A cross shape looks just like a plus sign. To do this, the computer looks at every single empty square on the grid and checks in all four directions. It looks up, down, left, and right to see how far it can travel before hitting a mine or the edge of the grid. It counts how many empty spaces it sees in each direction. Once it knows those distances, it picks the smallest number among them because that tells us how long the arms of the plus sign can be. By checking every spot this way, the code figures out the largest possible plus sign that fits perfectly between the mines.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.92 | σ = 1.98

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
gouthampradhan Java
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
gouthampradhan Java
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
zfang399 C++
27 links | 16 authors | 8 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 medium
2 solutions   September 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality