Number of Ships in a Rectangle - Solution & Explanation
Problem Statement
(This problem is an interactive problem.)
Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship.
You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary.
Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle.
Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
Example :
Input: ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0] Output: 3 Explanation: From [0,0] to [4,4] we can count 3 ships within the range.
Example 2:
Input: ans = [[1,1],[2,2],[3,3]], topRight = [1000,1000], bottomLeft = [0,0] Output: 3
Constraints:
- On the input
shipsis only given to initialize the map internally. You must solve this problem "blindfolded". In other words, you must find the answer using the givenhasShipsAPI, without knowing theshipsposition. 0 <= bottomLeft[0] <= topRight[0] <= 10000 <= bottomLeft[1] <= topRight[1] <= 1000topRight != bottomLeft
Approach Overview
Problem Overview: You are given an interactive API Sea.hasShips(topRight, bottomLeft) that returns whether at least one ship exists inside a rectangle. The grid is hidden, and you must count the exact number of ships within a given rectangle while minimizing API calls.
The key constraint: you cannot directly inspect grid cells. The only operation available is querying whether a region contains at least one ship. Because of that limitation, the solution relies heavily on divide and conquer to recursively split the search space.
Approach 1: Brute Force Grid Scan (O(N × M) time, O(1) space)
The naive idea is to check every coordinate inside the rectangle and determine if a ship exists there. In a normal grid problem, you would iterate through all cells using nested loops and count ships directly. However, the API does not allow checking individual cells unless you form a rectangle query for each coordinate.
This leads to a large number of API calls. For a rectangle of size N × M, the algorithm would issue up to N × M queries. Because interactive problems often restrict the number of API calls, this approach quickly becomes impractical. It also ignores the valuable pruning information returned by hasShips.
Approach 2: Recursion + Divide and Conquer (O(S log A) time, O(log A) space)
The optimal strategy recursively splits the rectangle into smaller regions. Start by calling hasShips(topRight, bottomLeft). If the API returns false, the region contains zero ships and you immediately stop exploring that branch. This pruning step prevents unnecessary work.
If the API returns true and the rectangle represents a single point (x1 == x2 and y1 == y2), you found exactly one ship. Otherwise, divide the rectangle into four quadrants using the midpoint and recursively search each sub-rectangle. This approach behaves like a quadtree search.
The efficiency comes from the fact that recursion only expands regions that actually contain ships. If the maximum number of ships is S, the algorithm performs roughly O(S log A) API calls where A is the area of the search space. The recursion depth is logarithmic because the rectangle keeps shrinking.
This technique is a classic example of divide and conquer combined with pruning in an interactive problem. Instead of scanning the entire array-like grid, the algorithm quickly eliminates empty regions.
Recommended for interviews: Recursion with divide and conquer is the expected solution. Interviewers want to see that you use the API result to prune large empty regions instead of checking every coordinate. Demonstrating the brute-force idea first shows baseline understanding, but implementing the recursive quadrant split proves you can optimize API-bound problems.
Solution
Since there are at most 10 ships in the rectangle, we can divide the rectangle into four sub-rectangles, calculate the number of ships in each sub-rectangle, and then add the number of ships in the four sub-rectangles. If there are no ships in a sub-rectangle, then there is no need to continue dividing.
The time complexity is O(C times log max(m, n)), and the space complexity is O(log max(m, n)). Where C is the number of ships, and m and n are the length and width of the rectangle, respectively.
Code
Python
Java
C++
Go
TypeScript
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Coordinate Scan | O(N × M) | O(1) | Conceptual baseline when direct grid access is available |
| Recursion + Divide and Conquer (Quadrant Split) | O(S log A) | O(log A) | Interactive API problems where empty regions can be pruned efficiently |
Video Solution
5136 Number of Ships in a Rectangle (Biweekly Contest 14) • Kelvin Chandra • 2,056 views views
Watch 2 more video solutions →Frequently Asked Questions
Is Number of Ships in a Rectangle easy or hard?
Number of Ships in a Rectangle Python/Java solution
How to solve Number of Ships in a Rectangle in O(S log N)?
What is the best approach for Number of Ships in a Rectangle?
Is Number of Ships in a Rectangle asked at Google/Amazon/Meta?
What data structure is used in Number of Ships in a Rectangle?
What is the time complexity of Number of Ships in a Rectangle?
Ready to solve this problem?
Practice Number of Ships in a Rectangle with our built-in code editor and test cases.
Practice on FleetCode