Marco Rossi·
The binary search that's actually correct — off-by-one traps removed
Implements algorithms with multiple complexity variants, step-by-step explanations, and complexity analysis.
Algorithm Implementation & Visualization
You are a computer science professor implementing an algorithm for production use. Implement the following algorithm with full analysis.
## Algorithm to Implement
{{algorithm_description}}
## Requirements
- Language: {{programming_language}}
- Input constraints: {{input_constraints}}
- Performance target: {{performance_target}}
- Memory limit: {{memory_constraint}}
## Deliverables
1. **Algorithm Explanation** - How it works with a worked example (step-by-step trace on sample input)
2. **Naive Implementation** - Simple, correct version for understanding
3. **Optimized Implementation** - Production-ready version with:
- Best possible time complexity
- Space-efficient data structures
- Early termination where possible
- Handling of all edge cases
4. **Alternative Approach** - If multiple valid approaches exist, show the trade-off
5. **Complexity Analysis** - Time and space Big O with proof/justification
6. **Test Cases** - Comprehensive tests including:
- Basic cases
- Edge cases (empty, single element, max size)
- Stress tests
- Randomized property-based tests if applicable
7. **ASCII Visualization** - Step-by-step trace showing data transformations
Write clean, self-documenting code. Include comments explaining the invariant at each step.
Ergebnisse
## Binary Search — with the off-by-one traps removed
The bug in 90% of hand-written binary searches is the `mid` overflow and the `<=` vs `<` boundary. Here's the version that's actually correct.
```typescript
/** Returns the index of `target`, or -1. Array must be sorted ascending. */
function binarySearch(arr: number[], target: number): number {
let lo = 0, hi = arr.length - 1;
while (lo <= hi) { // <= : the lo===hi case must be checked
const mid = lo + ((hi - lo) >> 1); // avoids (lo+hi) integer overflow
if (arr[mid] === target) return mid;
if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
```
**Trace — searching for `7` in `[1, 3, 7, 9, 11]`:**
```
lo hi mid arr[mid]
0 4 2 7 → match, return 2
```
| | Time | Space |
|---|------|-------|
| Worst case | O(log n) | O(1) |
| 1M elements | ≤20 steps | constant |
**Invariant:** at every iteration, if `target` exists it lies within `[lo, hi]`. The `>> 1` and `lo + (...)` form is the canonical overflow-safe midpoint. Want the lower-bound variant for insertion points?
Modell: Claude Sonnet 4
47 Likes21 SavesScore: 37
3 Kommentare
Ahmed Hassan·
Okay this code generation output just saved me an afternoon.
Emily Chen·
I'd ship this as-is. Maybe rename one var, that's it.
Lena Fischer·
The abort/cleanup detail is underrated. Most people forget it and leak memory.