Compact occupied ranges while preserving their exact union.
Compact occupied ranges while preserving their exact union. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.
Before you start
Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.
Build and check
Save the source as merge-half-open-intervals-python.py.
Save the example JSON below as request.json.
Run python3 merge-half-open-intervals-python.py < request.json.
Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.
Limits to understand
Input is limited to 20000 bytes and 500 intervals; endpoints must be JSON integers between -1000000000 and 1000000000, with start strictly less than end.
Only half-open integer intervals are supported. Adjacent intervals are merged; dates, timezones, floating-point endpoints, and additional object fields are rejected.
Input exactly {"intervals":array of at most 500 two-element arrays [start,end]}. Each endpoint is an integer -1000000000..1000000000; booleans forbidden; require start<end.
Sort by start then end. Merge overlapping or adjacent intervals when next_start<=current_end. Output {"intervals":sorted_merged_ranges,"covered":sum(end-start)}.
Intervals are half-open [start,end), not dates. No timezone or continuous floating-point intervals.
The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.
This browser preview builds code locally. It does not contact an API or run the code.
Default example ready.
Python example
import json
import sys
class InvalidInput(ValueError):
pass
def reject_number(_text):
raise InvalidInput()
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise InvalidInput()
result[key] = value
return result
def solve():
if len(sys.argv) != 1:
raise InvalidInput()
raw = sys.stdin.buffer.read(20001)
if len(raw) > 20000:
raise InvalidInput()
text = raw.decode('utf-8', errors='strict')
data = json.loads(
text,
object_pairs_hook=unique_object,
parse_float=reject_number,
parse_constant=reject_number,
)
if type(data) is not dict or set(data) != {'intervals'}:
raise InvalidInput()
intervals = data['intervals']
if type(intervals) is not list or len(intervals) > 500:
raise InvalidInput()
# The exact schema admits no arbitrary strings, so any decoded
# unpaired surrogate necessarily fails these schema checks.
for interval in intervals:
if type(interval) is not list or len(interval) != 2:
raise InvalidInput()
start, end = interval
if type(start) is not int or type(end) is not int:
raise InvalidInput()
if not (-1000000000 <= start < end <= 1000000000):
raise InvalidInput()
intervals.sort(key=lambda interval: (interval[0], interval[1]))
merged = []
for start, end in intervals:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
covered = sum(end - start for start, end in merged)
return json.dumps(
{'intervals': merged, 'covered': covered},
separators=(',', ':'),
allow_nan=False,
) + '\n'
def main():
try:
output = solve()
except (ValueError, TypeError, RecursionError, OverflowError, OSError):
sys.stderr.write('Invalid input\n')
return 2
sys.stdout.write(output)
return 0
if __name__ == '__main__':
sys.exit(main())
What to verify after running
Run the documented example and compare the JSON result.
Confirm malformed requests exit 2 without copying input data into diagnostic messages.
23 independent CLI cases passed on this exact source, including an unexpected-argument check.
Request or format preview
Illustrative preview. No provider response, price or balance is fetched.
Code license: MIT. Keep the license notice with your copy.
Example version 1.0.0 · Documentation reviewed 2026-11-17.
23 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.