Leetcode #1274: Number of Ships in a Rectangle
In this guide, we solve Leetcode #1274 Number of Ships in a Rectangle in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Array, Divide and Conquer, Interactive
Intuition
The problem splits naturally into smaller subproblems.
Solving each part independently makes the whole problem manageable.
Approach
Divide the input, solve recursively, then merge results.
This structure often yields clean and efficient code.
Steps:
- Divide into subproblems.
- Solve recursively.
- Merge to get final answer.
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.
Python Solution
# """
# This is Sea's API interface.
# You should not implement it, or speculate about its implementation
# """
# class Sea:
# def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool:
#
# class Point:
# def __init__(self, x: int, y: int):
# self.x = x
# self.y = y
class Solution:
def countShips(self, sea: "Sea", topRight: "Point", bottomLeft: "Point") -> int:
def dfs(topRight, bottomLeft):
x1, y1 = bottomLeft.x, bottomLeft.y
x2, y2 = topRight.x, topRight.y
if x1 > x2 or y1 > y2:
return 0
if not sea.hasShips(topRight, bottomLeft):
return 0
if x1 == x2 and y1 == y2:
return 1
midx = (x1 + x2) >> 1
midy = (y1 + y2) >> 1
a = dfs(topRight, Point(midx + 1, midy + 1))
b = dfs(Point(midx, y2), Point(x1, midy + 1))
c = dfs(Point(midx, midy), bottomLeft)
d = dfs(Point(x2, midy), Point(midx + 1, y1))
return a + b + c + d
return dfs(topRight, bottomLeft)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.