Number of Ships in a Rectangle - Problem

This 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.

Input & Output

Example 1 — Basic Rectangle Search
$ Input: ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0]
Output: 3
💡 Note: Rectangle from [0,0] to [4,4] contains ships at [1,1], [2,2], and [3,3]. Ship at [5,5] is outside the rectangle.
Example 2 — Smaller Rectangle
$ Input: ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [2,2], bottomLeft = [1,1]
Output: 2
💡 Note: Rectangle from [1,1] to [2,2] contains ships at [1,1] and [2,2] only.
Example 3 — No Ships in Range
$ Input: ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [0,0], bottomLeft = [0,0]
Output: 0
💡 Note: Single point [0,0] contains no ships.

Constraints

  • On the given rectangle, there are at most 10 ships.
  • The length of each dimension of the rectangle is at most 1000.
  • You can make at most 400 calls to hasShips.
  • topRight != bottomLeft

Visualization

Tap to expand
Ship Detection: Find Ships in Rectangle [0,0] to [4,4]Search Rectangle[1,1] ✓[2,2] ✓[3,3] ✓[5,5] ✗Interactive Problem✓ Ships in rectangle: 3✗ Ship outside rectangle: 1API calls must be ≤ 400Use hasShips() efficiently!Output: 3 ships found in rectangle
Understanding the Visualization
1
Input Ships & Rectangle
Ships at coordinates and search rectangle bounds
2
API Constraint
Use hasShips(topRight, bottomLeft) efficiently (≤400 calls)
3
Count Result
Return number of ships within rectangle bounds
Key Takeaway
🎯 Key Insight: Use divide and conquer to minimize API calls by only searching regions that contain ships
Asked in
Google 45 Facebook 32
18.5K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen