There exists an infinite number line, with its origin at 0 and extending towards the positive x-axis. You are given a 2D array queries, which contains two types of queries:
For a query of type 1, queries[i] = [1, x]. Build an obstacle at distance x from the origin. It is guaranteed that there is no obstacle at distance x when the query is asked.
For a query of type 2, queries[i] = [2, x, sz]. Check if it is possible to place a block of size sz anywhere in the range [0, x] on the line, such that the block entirely lies in the range [0, x]. A block cannot be placed if it intersects with any obstacle, but it may touch it. Note that you do not actually place the block. Queries are separate.
Return a boolean array results, where results[i] is true if you can place the block specified in the i-th query of type 2, and false otherwise.
Input & Output
Example 1 — Basic Operations
$Input:queries = [[1,2],[2,3,3],[2,5,2]]
›Output:[false,true]
💡 Note:Add obstacle at 2. Check if size-3 block fits in [0,3]: gap 0→2 is size 2, gap 2→3 is size 1, max gap < 3, so false. Check if size-2 block fits in [0,5]: gap 2→5 is size 3 ≥ 2, so true.
Example 2 — Multiple Obstacles
$Input:queries = [[1,1],[1,4],[2,6,2],[2,6,3]]
›Output:[true,false]
💡 Note:Add obstacles at 1 and 4. Check size-2 block in [0,6]: gaps are 0→1(1), 1→4(2), 4→6(2), max gap=2≥2, so true. Check size-3 block: max gap=2<3, so false.
Example 3 — No Obstacles
$Input:queries = [[2,5,3],[1,2],[2,5,6]]
›Output:[true,false]
💡 Note:Check size-3 block in [0,5] with no obstacles: entire range has size 6≥3, so true. Add obstacle at 2. Check size-6 block: max gap is now 3<6, so false.
The key insight is to track gaps between obstacles and find the maximum available space. The optimal approach uses TreeMap/sorted list with binary search for O(q log n) time complexity. Time: O(q log n), Space: O(n).
Common Approaches
✓
Binary Search with TreeMap
⏱️ Time: O(q × log n)
Space: O(n)
Maintain obstacles in a TreeMap for O(log n) insertions and range queries. For block placement, use binary search to find obstacles within range and calculate gaps efficiently.
Brute Force with Set
⏱️ Time: O(q × x)
Space: O(n)
For each type-2 query, iterate through all possible starting positions and check if the block can fit without intersecting any obstacles. Use a set to store obstacle positions for O(1) lookup.
Sorted List with Gap Tracking
⏱️ Time: O(q × n)
Space: O(n)
Keep obstacles in a sorted list and for each block placement query, find the largest gap between consecutive obstacles. If the largest gap is ≥ block size, placement is possible.
Binary Search with TreeMap — Algorithm Steps
Use TreeMap to store obstacles with O(log n) operations
Binary search to find obstacles in query range
Calculate gaps and find maximum gap efficiently
Visualization
Tap to expand
Step-by-Step Walkthrough
1
TreeMap Storage
Maintain obstacles in sorted TreeMap for fast operations
2
Binary Search Range
Use binary search to find obstacles ≤ x
3
Calculate Max Gap
Find largest gap in O(k) time where k = obstacles in range
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_OBSTACLES 10000
#define MAX_QUERIES 10000
#define MAX_LINE 100000
static int obstacles[MAX_OBSTACLES];
static bool results[MAX_QUERIES];
int compare_ints(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int bisect_right(int arr[], int n, int target) {
int left = 0, right = n;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] <= target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
void insert_sorted(int arr[], int *n, int value) {
int pos = 0;
while (pos < *n && arr[pos] < value) {
pos++;
}
for (int i = *n; i > pos; i--) {
arr[i] = arr[i-1];
}
arr[pos] = value;
(*n)++;
}
int solution(int queries[][3], int query_sizes[], int num_queries, bool* results) {
int obstacle_count = 0;
int result_count = 0;
for (int i = 0; i < num_queries; i++) {
if (queries[i][0] == 1) { // Add obstacle
insert_sorted(obstacles, &obstacle_count, queries[i][1]);
} else { // Check block placement
int x = queries[i][1], sz = queries[i][2];
// Find obstacles in range [0, x] using binary search
int right_idx = bisect_right(obstacles, obstacle_count, x);
// Find maximum gap
int max_gap = 0;
if (right_idx == 0) {
max_gap = x + 1;
} else {
// Gap from 0 to first obstacle
if (obstacles[0] > max_gap) {
max_gap = obstacles[0];
}
// Gaps between consecutive obstacles
for (int j = 1; j < right_idx; j++) {
int gap = obstacles[j] - obstacles[j-1] - 1;
if (gap > max_gap) {
max_gap = gap;
}
}
// Gap from last obstacle to x
int gap = x - obstacles[right_idx-1];
if (gap > max_gap) {
max_gap = gap;
}
}
results[result_count++] = (max_gap >= sz);
}
}
return result_count;
}
int parse_queries(char* line, int queries[][3], int query_sizes[]) {
int query_count = 0;
char* ptr = line + 1; // skip first '['
while (*ptr && query_count < MAX_QUERIES) {
if (*ptr == '[') {
ptr++;
int nums[3];
int num_count = 0;
while (*ptr && *ptr != ']' && num_count < 3) {
while (*ptr == ' ' || *ptr == ',') ptr++;
if (*ptr >= '0' && *ptr <= '9') {
nums[num_count] = strtol(ptr, &ptr, 10);
num_count++;
}
}
if (num_count > 0) {
for (int i = 0; i < num_count; i++) {
queries[query_count][i] = nums[i];
}
query_sizes[query_count] = num_count;
query_count++;
}
}
ptr++;
}
return query_count;
}
int main() {
char line[MAX_LINE];
if (!fgets(line, sizeof(line), stdin)) {
return 1;
}
int queries[MAX_QUERIES][3];
int query_sizes[MAX_QUERIES];
int num_queries = parse_queries(line, queries, query_sizes);
int result_count = solution(queries, query_sizes, num_queries, results);
printf("[");
for (int i = 0; i < result_count; i++) {
printf(results[i] ? "true" : "false");
if (i < result_count - 1) printf(",");
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(q × log n)
Each query performs O(log n) operations on TreeMap, and gap calculation is O(k) where k is obstacles in range
n
2n
✓ Linear Growth
Space Complexity
O(n)
TreeMap stores up to n obstacle positions
n
2n
⚡ Linearithmic Space
28.5K Views
MediumFrequency
~35 minAvg. Time
890 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.