OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Find overlaps between bounded integer intervals with Python

Python

Report overlapping half-open intervals using original one-based positions.

Python code excerpt: Find overlaps between bounded integer intervals with Python. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Report overlapping half-open intervals using original one-based positions. This is a local data check under the documented conventions; it does not execute tools or contact a service.

Before you start

  • Save the code as recipe.py and run python3.12 recipe.py with JSON supplied on stdin. No arguments, including a help option, are accepted. The CLI imports only json, sys and math.
  • Input must be an array of at most 20 objects. Each object must contain start and end as integers, excluding booleans, from 0 through 1000000000 inclusive, with start < end. Additional fields are ignored after JSON parsing.
  • Intervals are half-open: [start, end). Touching endpoints do not overlap. Positions are the original one-based array positions, and results are ordered by first and then second. Offsets are unitless, not dates or timezone values.
  • Success exits 0 and writes exactly one JSON object to stdout without stderr. An empty input array returns {"overlaps":[]}. Invalid input, arguments or stdin read failures exit 2 with no stdout and the generic lowercase stderr diagnostic error: invalid input.
  • Input is decoded as strict UTF-8. A leading UTF-8 BOM, malformed JSON, NaN, Infinity, -Infinity and floating-point overflow are rejected. Python's JSON convention for duplicate object keys applies: the last occurrence is used.
  • The CLI reads stdin only; it does not open input paths, write files, execute external commands or contact a network.

Build and check

  1. Use Python 3.12. Save the code as recipe.py.
  2. Save the supplied JSON example as input.json, encoded as UTF-8 without a BOM.
  3. Run: python3 recipe.py < input.json
  4. Compare the output with the expected result; handle exit code 2 as invalid input.

Limits to understand

  • Reads at most 65537 bytes and rejects input exceeding 65536 bytes, including whitespace. Stdin can block while waiting for EOF.
  • The input bytes, decoded text, parsed JSON and results are held in memory. The byte limit bounds source input size, not exact memory consumption; parsed structures add overhead.
  • At most 190 interval pairs are checked and at most 190 overlap records are returned.
  • Successful output reveals original positions and overlapping ranges and may therefore be sensitive.
  • Output-write failures, including stdout flush failures, are outside the stated exit-code and diagnostic guarantee.
  • The interpreter's integer-conversion and JSON nesting limits can also cause input rejection. No provider integration, production suitability or uniqueness is claimed.

Run it

python3 recipe.py < input.json

Example input

[{"start": 0, "end": 5}, {"start": 3, "end": 7}]

Expected output

{"overlaps": [{"first": 1, "second": 2, "start": 3, "end": 5}]}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

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
import math


def reject_constant(text):
    raise ValueError('invalid input')


def finite_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise ValueError('invalid input')
    return value


def process_input():
    if len(sys.argv) != 1:
        raise ValueError('invalid input')

    raw = sys.stdin.buffer.read(65537)
    if len(raw) > 65536 or raw.startswith(b'\xef\xbb\xbf'):
        raise ValueError('invalid input')
    text = raw.decode('utf-8', errors='strict')
    records = json.loads(
        text,
        parse_constant=reject_constant,
        parse_float=finite_float,
    )

    if not isinstance(records, list) or len(records) > 20:
        raise ValueError('invalid input')

    intervals = []
    for record in records:
        if not isinstance(record, dict):
            raise ValueError('invalid input')
        if 'start' not in record or 'end' not in record:
            raise ValueError('invalid input')
        start = record['start']
        end = record['end']
        for value in (start, end):
            if isinstance(value, bool) or not isinstance(value, int):
                raise ValueError('invalid input')
            if not 0 <= value <= 1000000000:
                raise ValueError('invalid input')
        if start >= end:
            raise ValueError('invalid input')
        intervals.append((start, end))

    overlaps = []
    for i in range(len(intervals)):
        for j in range(i + 1, len(intervals)):
            start = max(intervals[i][0], intervals[j][0])
            end = min(intervals[i][1], intervals[j][1])
            if start < end:
                overlaps.append({
                    'first': i + 1,
                    'second': j + 1,
                    'start': start,
                    'end': end,
                })
    return {'overlaps': overlaps}


def main():
    try:
        result = process_input()
    except Exception:
        sys.stderr.write('error: invalid input\n')
        return 2

    sys.stdout.write(json.dumps(result, separators=(',', ':')) + '\n')
    sys.stdout.flush()
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • The supplied example must match the documented JSON output.
  • Error cases must exit 2 with no stdout. Review sensitive successful output before sharing it.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-14.

    Six independent CLI fixtures and 10 curated supplementary checks passed in the pinned offline Python 3.12 container. This does not establish exhaustive correctness, production performance or compatibility with an external provider.