File: search-insert-position/solution.py

Date: 2026-06-06

Time: 19:00

search-insert-position/solution.py

Purpose

This file solves LeetCode #35 — Search Insert Position. It provides a single function that either finds a target value in a sorted array or determines where it should be inserted to maintain sort order. This is the canonical "lower bound" binary search — the same operation as bisect_left in Python's standard library.

Key Components

searchInsert(nums, target) -> int — The sole public function. Contract:

Patterns

Standard binary search with left-biased convergence. The loop maintains the invariant that the answer lies in [left, right + 1]. When the loop exits (left > right), left has converged to the insertion point. This is the textbook "find leftmost position" variant — no off-by-one post-processing needed because left naturally lands at the correct spot.

The function follows LeetCode's method-signature convention (camelCase searchInsert, List[int] typing) rather than PEP 8, which is standard across this repo.

Dependencies

Flow

1. Initialize left = 0, right = len(nums) - 1.

2. Loop while left <= right:

3. If the loop exits without finding target, return left — the insertion index.

Each iteration halves the search space, giving O(log n) time and O(1) space.

Invariants

Error Handling

None. The function trusts its inputs entirely — no bounds checking, no type validation. An empty nums list works correctly: right starts at -1, the loop never executes, and left = 0 is returned. This is appropriate for a LeetCode solution where the problem statement guarantees valid input.

Topics to Explore

Beliefs