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
Number of Ships in a Rectangle INPUT 0 1 2 3 4 5 0 1 2 3 4 5 S S S S ships = [[1,1],[2,2],[3,3],[5,5]] topRight = [4,4] bottomLeft = [0,0] Query: hasShips() max 400 calls allowed S = Ship location ALGORITHM STEPS 1 Check hasShips() If false, return 0 2 Single Point? If single point, return 1 3 Divide into 4 Split rectangle into quadrants 4 Recurse + Sum Count ships in each quadrant Divide and Conquer Split into 4 Q1 Q2 Q3 Q4 Recurse each O(S * log(max(m,n))) FINAL RESULT 1 2 3 X [5,5] Outside OUTPUT 3 3 ships found in rectangle [1,1], [2,2], [3,3] are inside [5,5] is outside query area Key Insight: Use Divide and Conquer: recursively split rectangle into 4 quadrants and only explore quadrants where hasShips() returns true. This ensures O(S * log(area)) calls where S is number of ships, staying well under the 400 call limit. Ship at [5,5] is excluded as it's outside the query range. TutorialsPoint - Number of Ships in a Rectangle | Divide and Conquer Approach
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