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.
The key insight is to use divide and conquer to efficiently search only regions containing ships. Instead of checking each coordinate individually, recursively divide the rectangle into quadrants and only explore areas where hasShips returns true. Best approach is divide and conquer with Time: O(log(area) × ships), Space: O(log(area)).
Common Approaches
✓
Brute Force - Check Every Point
⏱️ Time: O(w × h)
Space: O(1)
Iterate through every possible coordinate in the rectangle and use hasShips to check if there's a ship at that single point. This is straightforward but inefficient as it makes one API call per coordinate.
Divide and Conquer - Recursive Search
⏱️ Time: O(log(area) × ships)
Space: O(log(area))
Use divide and conquer strategy to recursively split the rectangle into smaller regions. Only explore regions that contain ships according to hasShips API. When region becomes a single point, we've found a ship.
Brute Force - Check Every Point — Algorithm Steps
Iterate through all x coordinates from bottomLeft[0] to topRight[0]
For each x, iterate through all y coordinates from bottomLeft[1] to topRight[1]
Call hasShips for each single coordinate
Count total ships found
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Grid Setup
Mark all coordinates in the rectangle
2
Sequential Check
Check each coordinate one by one
3
Count Ships
Count found ships and return total
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SHIPS 100
typedef struct {
int ships[MAX_SHIPS][2];
int count;
} Sea;
void initSea(Sea* sea, int shipArray[][2], int shipCount) {
sea->count = shipCount;
for (int i = 0; i < shipCount; i++) {
sea->ships[i][0] = shipArray[i][0];
sea->ships[i][1] = shipArray[i][1];
}
}
int hasShips(Sea* sea, int topRight[2], int bottomLeft[2]) {
for (int x = bottomLeft[0]; x <= topRight[0]; x++) {
for (int y = bottomLeft[1]; y <= topRight[1]; y++) {
for (int i = 0; i < sea->count; i++) {
if (sea->ships[i][0] == x && sea->ships[i][1] == y) {
return 1;
}
}
}
}
return 0;
}
int solution(Sea* sea, int topRight[2], int bottomLeft[2]) {
int count = 0;
for (int x = bottomLeft[0]; x <= topRight[0]; x++) {
for (int y = bottomLeft[1]; y <= topRight[1]; y++) {
int point[2] = {x, y};
if (hasShips(sea, point, point)) {
count++;
}
}
}
return count;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int parseShips(const char* line, int ships[][2]) {
int count = 0;
const char* p = line;
// Skip initial '['
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']' && count < MAX_SHIPS) {
// Skip whitespace and commas
while (*p == ' ' || *p == ',') p++;
// Check for end
if (*p == ']' || *p == '\0') break;
// Expect '['
if (*p != '[') {
p++;
continue;
}
p++; // skip '['
// Parse first coordinate
ships[count][0] = (int)strtol(p, (char**)&p, 10);
// Skip comma
while (*p == ' ' || *p == ',') p++;
// Parse second coordinate
ships[count][1] = (int)strtol(p, (char**)&p, 10);
// Skip to closing ']'
while (*p && *p != ']') p++;
if (*p == ']') p++;
count++;
}
return count;
}
void parseCoord(const char* line, int coord[2]) {
const char* p = line;
while (*p && *p != '[') p++;
if (*p == '[') p++;
coord[0] = (int)strtol(p, (char**)&p, 10);
while (*p == ' ' || *p == ',') p++;
coord[1] = (int)strtol(p, (char**)&p, 10);
}
int main() {
char line[1000];
int ships[MAX_SHIPS][2];
int topRight[2], bottomLeft[2];
fgets(line, sizeof(line), stdin);
int shipCount = parseShips(line, ships);
fgets(line, sizeof(line), stdin);
parseCoord(line, topRight);
fgets(line, sizeof(line), stdin);
parseCoord(line, bottomLeft);
Sea sea;
initSea(&sea, ships, shipCount);
printf("%d\n", solution(&sea, topRight, bottomLeft));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(w × h)
Must check every coordinate in width × height rectangle
n
2n
⚡ Linearithmic
Space Complexity
O(1)
Only uses a few variables for counting and iteration
n
2n
✓ Linear Space
18.5K Views
MediumFrequency
~25 minAvg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.