← Questions

Largest square subgrid with every sum under a limit

0
OpenAICodingLast asked Dec 2021

A coding interview question asked in OpenAI's agentic coding (beta) round, last asked Dec 2021. It tests prefix sums, binary-search and matrices.

You get an integer grid and a limit max_sum. A side length k is valid when every contiguous k x k square in the grid sums to at most max_sum. Return the largest valid side length, or 0 when none is valid.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • largest_square(grid: list[list[int]], max_sum: int) -> int

Example

largest_square([[1,1,1],[1,1,1],[1,1,1]], 4)  -> 2   # every 2x2 sums to 4; the 3x3 sums to 9
largest_square([[1,1,3],[1,1,1],[1,1,1]], 4)  -> 1   # the top-right 2x2 sums to 6
largest_square([[1,2],[3,4]], 3)              -> 0   # the cell 4 already breaks k = 1
largest_square([[5,-5],[-5,5]], 0)            -> 2   # with negatives, k = 1 fails but k = 2 holds

Constraints

  • Up to 300 x 300 cells.
  • Sums can exceed 32 bits on large grids.

Clarifying questions

  • Can values be negative? That decides whether binary search on k is safe.
  • Is it "every" square of side k, or "some" square?
  • What should be returned when no k works?
  • Is the grid always rectangular and non-empty?

What a strong answer covers

  • A 2D prefix sum so any square's sum costs O(1).
  • Checking one k in O(rows x cols); with non-negative values validity is monotone (a valid k means every smaller k is valid), so binary search gives O(rows x cols x log(min(rows, cols))).
  • With negative values validity is not monotone (the last example), so check every k from the largest down: O(rows x cols x min(rows, cols)).
  • Tests at both extremes: no valid k, and the whole grid valid.

Follow-ups

  • The "some square" version: the largest k such that at least one k x k square is within the limit.
  • Rectangles instead of squares.
  • Many queries with different limits on the same grid.

Where it's asked

  • OpenAI · Agentic coding (beta) · Last asked Dec 2021An existing codebase and changes too large to write by hand; you work through them with an AI coding agent · An AI coding agent is expected

What it tests

prefix sums · binary-search · matrices

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding