Sorting and Searching Algorithms Questions
Comparison and non-comparison sorting (quicksort with its pivot and partition choices and hybrid cutoffs, mergesort, heapsort as a sort, insertion/selection/bubble, counting/radix/bucket), their stability, in-place behavior, stack depth and lower bounds, and choosing a sort from input constraints, including near-sorted data, library sorts (Timsort, introsort, language defaults), comparator design and expensive comparisons or copies. Also selection (quickselect, median-of-medians, nth_element), external merge sorting of data larger than memory (run generation and merge passes), and binary search with its variants: first/last occurrence, lower/upper bound, rotated arrays with or without duplicates, peak and mountain arrays, sorted matrices, unbounded search, loop-invariant correctness and off-by-one pitfalls, and binary search on an answer space (discrete or continuous, including k-th smallest by value). Includes divide-and-conquer reasoning for sorts (merge step, merging sorted arrays, median of two sorted arrays, inversion counting). Excludes heap data-structure mechanics and heap-based top-k and k-way merging, trees and tries, general graph search, distributed data-processing systems, approximate nearest-neighbor and streaming-sketch algorithms, and abstract Big-O comparison.
Explain what 'stable sort' and 'in-place sort' mean with concrete examples. Given the list of tuples [(name, age)]: [('alice', 30), ('bob', 25), ('carol', 30)], show a stable and an unstable sort by age and explain why stability matters in multi-key sorting.
Sample Answer
The idea in plain words
- A sort is stable if records with equal keys come out in the same relative order they went in. Sorting
[('alice', 30), ('bob', 25), ('carol', 30)]by age, alice and carol tie at 30. A stable sort must put alice before carol, because alice came first. An unstable sort is allowed to swap them. - A sort is in place if it rearranges the list it was given using only a small, fixed amount of extra memory (a few variables, or a stack of about log n frames), instead of building a second list of the same size. In Python,
list.sort()changes the list and returnsNone;sorted()builds and returns a new list.
The two properties are independent. Insertion sort is stable and in place. Merge sort (array version) is stable but not in place. Quicksort and heapsort are in place but not stable. Python's list.sort is stable by documentation (the line from its docstring in the output below says so).
Terms used below: quicksort picks one row as the pivot and partitions the list, which means moving rows smaller than the pivot to its left and the others to its right, then repeats on each side. Heapsort arranges the rows into a heap (a structure whose largest row sits at the front), then repeatedly swaps the front row to the end. Timsort is the merge-and-insertion hybrid that Python's built-in sort uses. A tie-breaker is an extra key added at the end of the sort key so that rows with equal main keys still have one fixed order.
A stable and an unstable sort of the example
The program sorts the three tuples by age three ways: with sorted (stable), with a quicksort that uses the last element as the pivot (unstable), and with an in-place insertion sort (stable). Then it shows the in-place versus new-list difference, multi-key sorting, and a pagination example.
import random
def quicksort_by_age(rows, trace=False):
"""In-place quicksort, last element as pivot, strict < in the partition. Not stable."""
def sort(lo, hi):
if lo >= hi:
return
pivot, i = rows[hi][1], lo
for j in range(lo, hi):
if rows[j][1] < pivot:
rows[i], rows[j] = rows[j], rows[i]
if trace:
print(f" swap slots {i} and {j} (a smaller-than-pivot row moves left):", [r[0] for r in rows])
i += 1
rows[i], rows[hi] = rows[hi], rows[i]
if trace:
print(f" swap pivot into slot {i}:", [r[0] for r in rows])
sort(lo, i - 1)
sort(i + 1, hi)
sort(0, len(rows) - 1)
def insertion_by_age(rows):
"""In-place insertion sort. Stable: shifts only while the left item is strictly greater."""
for i in range(1, len(rows)):
item, j = rows[i], i - 1
while j >= 0 and rows[j][1] > item[1]:
rows[j + 1] = rows[j]
j -= 1
rows[j + 1] = item
people = [("alice", 30), ("bob", 25), ("carol", 30)]
stable = sorted(people, key=lambda p: p[1])
print("stable (sorted by age):", stable)
unstable = list(people)
print("quicksort steps (pivot = last row, carol, age 30):")
quicksort_by_age(unstable, trace=True)
print("unstable (quicksort) :", unstable)
in_place = list(people)
insertion_by_age(in_place)
print("insertion sort, in place:", in_place)
print("list.sort says:", " ".join(list.sort.__doc__.split("\n\n")[1].split()))
# in-place vs new list
original = list(people)
returned = original.sort(key=lambda p: p[1])
print("list.sort() returns", returned, "and changed the list itself:", original)
copy = sorted(people, key=lambda p: p[1])
print("sorted() left the input alone:", people, "and built a new list:", copy)
# Multi-key sorting with successive stable sorts: department ascending, then age descending.
staff = [("dana", "ops", 41), ("eli", "dev", 30), ("fay", "ops", 41), ("gus", "dev", 35), ("hal", "ops", 29)]
step1 = sorted(staff, key=lambda r: r[2], reverse=True) # secondary key first
print("\nafter pass 1 (age desc):", [r[0] for r in step1])
step2 = sorted(step1, key=lambda r: r[1]) # primary key last
print("after pass 2 (dept asc):", [r[0] for r in step2])
print("fay and dana tie on both keys and keep input order:", step2.index(staff[0]) < step2.index(staff[2]))
# Paginated results: sorting only by age, with ties returned in an unspecified order.
users = [(f"user{i}", 20 + i % 3) for i in range(9)]
def fetch_page(page, size, seed):
rows = list(users)
random.Random(seed).shuffle(rows) # stands in for a store that orders ties arbitrarily
rows.sort(key=lambda r: r[1]) # stable, but the incoming tie order differs per request
return rows[page * size:(page + 1) * size]
page0 = fetch_page(0, 4, seed=1)
page1 = fetch_page(1, 4, seed=2)
page2 = fetch_page(2, 4, seed=3)
seen = [r[0] for r in page0 + page1 + page2]
print("\nage-only paging, rows seen:", len(seen), "distinct:", len(set(seen)))
missing = sorted(set(u[0] for u in users) - set(seen))
print("never shown:", missing)
def fetch_page_fixed(page, size, seed):
rows = list(users)
random.Random(seed).shuffle(rows)
rows.sort(key=lambda r: (r[1], r[0])) # tie-breaker: the unique name
return rows[page * size:(page + 1) * size]
seen = [r[0] for p, s in ((0, 1), (1, 2), (2, 3)) for r in fetch_page_fixed(p, 4, s)]
print("with (age, name) key, rows seen:", len(seen), "distinct:", len(set(seen)))
Run in a python:3.12 container (Python 3.12), it prints:
stable (sorted by age): [('bob', 25), ('alice', 30), ('carol', 30)]
quicksort steps (pivot = last row, carol, age 30):
swap slots 0 and 1 (a smaller-than-pivot row moves left): ['bob', 'alice', 'carol']
swap pivot into slot 1: ['bob', 'carol', 'alice']
unstable (quicksort) : [('bob', 25), ('carol', 30), ('alice', 30)]
insertion sort, in place: [('bob', 25), ('alice', 30), ('carol', 30)]
list.sort says: The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
list.sort() returns None and changed the list itself: [('bob', 25), ('alice', 30), ('carol', 30)]
sorted() left the input alone: [('alice', 30), ('bob', 25), ('carol', 30)] and built a new list: [('bob', 25), ('alice', 30), ('carol', 30)]
after pass 1 (age desc): ['dana', 'fay', 'gus', 'eli', 'hal']
after pass 2 (dept asc): ['gus', 'eli', 'dana', 'fay', 'hal']
fay and dana tie on both keys and keep input order: True
age-only paging, rows seen: 9 distinct: 7
never shown: ['user4', 'user8']
with (age, name) key, rows seen: 9 distinct: 9
Reading the output
- Stable:
[bob 25, alice 30, carol 30]. alice stays ahead of carol. - Unstable (the quicksort):
[bob 25, carol 30, alice 30]. The printed steps show it: the pivot is carol (age 30). The partition step swaps alice with bob (bob is smaller than the pivot), givingbob, alice, carol, and then the final swap that puts the pivot in place exchanges carol (slot 2) with alice (slot 1), givingbob, carol, alice. Alice has jumped over carol. Nothing is wrong with the result by age; only the order of equal keys changed. This is the kind of reordering swaps across a distance produce; it is not random. - Insertion sort only shifts elements that are strictly larger, so alice and carol never pass each other: stable and in place.
- In place versus new list:
list.sort(key=...)returnedNoneand the original list changed;sorted(...)left the input alone and built a new list. - The stability of Python's built-in sort is stated in its docstring. The program prints it from
list.sort.__doc__on Python 3.12: "The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained)."
Why stability matters: multi-key sorting
To sort by department ascending and, inside a department, by age descending, sort in successive passes starting with the least important key: first by age descending, then by department ascending. Because the second pass is stable, people in the same department keep the age order from the first pass. In the output, pass 1 gives dana, fay, gus, eli, hal (age 41, 41, 35, 30, 29) and pass 2 groups by department: gus, eli (dev), then dana, fay, hal (ops), each group still in age-descending order. dana and fay tie on both keys and stay in input order. If the second pass were unstable, the age order inside each department could be scrambled. Doing the passes in the other order (primary first) would let the last pass override it; the last sort always wins.
Stability and paginated results
Pagination means fetching a long sorted result in pages (rows 0 to 3, then 4 to 7, and so on), one request per page. A database or search store is allowed to return rows with equal sort keys in any order, and that order can differ from one request to the next. Sorting only by age in such a store, each page request can see ties in a different order, so a tied row can slip across a page boundary and be shown twice or never. The simulation shuffles the rows per request (to stand in for that), sorts by age, and takes pages of 4 rows: across three pages 9 rows are shown but only 7 distinct, and user4 and user8 are never shown. Adding a unique tie-breaker to the sort key, (age, name), makes the order total and deterministic: all 9 distinct rows appear exactly once. The rule: for any paginated or reproducible ordering, end the key with a unique column such as an id. A stable algorithm alone does not help when the input order itself changes between requests.
Complexity and when each property costs something
- Stable sorting in the standard library costs nothing extra to use: Python's sort is O(n log n) worst case and stable.
- Stable algorithms: insertion, bubble, merge, Timsort, counting sort. Unstable by default: selection (the swap version), quicksort, heapsort. Any unstable sort can be made stable by adding the original index as a final tie-breaker in the key, at the cost of O(n) extra memory for the indexes.
- In place means O(1) or O(log n) extra memory: insertion, selection, bubble, heap, and quicksort are in place; merge sort on arrays uses O(n) extra, so it is not.
Edge cases and common mistakes
- Stability only matters when keys can tie and the tied records can be told apart; sorting plain integers, a stable and an unstable result are the same list.
- Confusing "in place" with "stable": they are independent properties.
- Calling a sort in place when it uses an auxiliary array of size n.
- Assuming the sort a database or another library uses is stable; if you need a tie order, put it in the sort key.
- Doing the multi-key passes in the wrong order, or using
reverse=Trueand expecting ties to flip: Python'sreverse=Truekeeps equal elements in their original order, so it preserves stability.
Running the code
Save the program as stable_sort_demo.py and run:
python stable_sort_demo.py
Standard library only (random); no install or config needed.
Write a Java method to find the first (leftmost) occurrence of target in a sorted integer array that may contain duplicates. Signature: public static int firstOccurrence(int[] arr, int target). Explain loop invariants and boundary conditions to ensure correctness.
Sample Answer
Direct answer
To find the leftmost occurrence, do not stop when you see the target. Treat the problem as "find the first index whose value is greater than or equal to the target" (a lower bound), then check whether that index really holds the target. Equal values at mid push the window left (hi = mid), smaller values push it right (lo = mid + 1). If the lower-bound index is past the end or holds a different value, return -1. Time O(log n), space O(1).
The idea in plain words
In [1, 2, 2, 2, 2, 3, ...], the ordinary binary search returns as soon as it sees any 2, which could be index 2, 3 or 4. The first 2 sits at index 1, exactly at the boundary where values stop being "less than 2" and start being "at least 2". Because the array is sorted, all "less than target" values come first and all "at least target" values come after, so finding the leftmost target means finding that boundary.
Marking each value as "less than the target or not" makes the boundary visible. This small program prints the marks for the trace array and target 2:
arr = [1, 2, 2, 2, 2, 3, 5, 5, 8]
target = 2
print("index :", " ".join(f"{i:2d}" for i in range(len(arr))))
print("value :", " ".join(f"{v:2d}" for v in arr))
print("< 2 ? :", " ".join(" Y" if v < target else " N" for v in arr))
first_n = next(i for i, v in enumerate(arr) if v >= target)
print("the Y run ends before index", first_n, "so the first value >= 2 is at index", first_n)
Output (python:3.12):
index : 0 1 2 3 4 5 6 7 8
value : 1 2 2 2 2 3 5 5 8
< 2 ? : Y N N N N N N N N
the Y run ends before index 1 so the first value >= 2 is at index 1
The Ys (too small) come first and the Ns (big enough) after them, so the search is looking for the place where the Ys stop.
Brute force
A linear scan from index 0 returns the first match in O(n). Binary search with a walk to the left after finding a match is O(n) as well (all-equal input walks the whole array). The boundary search stays O(log n) even then.
Approach and invariant
Use a half-open window [lo, hi): lo is included, hi is not. Start with lo = 0 and hi = arr.length, so an empty array gives an empty window and the loop never runs.
Loop invariant, in words: every index to the left of lo holds a value smaller than the target, and every index at or after hi holds a value at least as big as the target. Only the positions between lo and hi are undecided. Each step keeps this true:
- If
arr[mid] < target, thenmidand everything left of it are too small, solo = mid + 1. - Otherwise
arr[mid] >= target, somidcould still be the first occurrence and must stay inside the window:hi = mid(notmid - 1).
The window shrinks every round (mid is always inside it, and either bound moves past or onto mid while the window is non-empty), so the loop ends with lo == hi, the boundary. By the invariant, lo is the first index whose value is at least the target, so the target is present exactly when lo < arr.length and arr[lo] == target.
Code
The mid is lo + (hi - lo) / 2, which cannot overflow a 32-bit int (unlike (lo + hi) / 2 when both are near 2^30 or more). The extra overload with trace prints lo, hi and mid so the steps can be followed; the required method is the two-argument one. Notes for readers coming from Python: int[] is Java's fixed-size array of 32-bit integers; two methods may share a name if their parameter lists differ (an overload, here the two-argument public method and the three-argument one with trace); AssertionError is the exception thrown by the program's own check when a result is wrong; and / between two Java int values is integer division that drops the fraction (7 / 2 is 3), so lo + (hi - lo) / 2 behaves like Python's // for the non-negative values used here. The main method runs the edge cases and compares against a linear scan on 5000 random sorted arrays (seed 42).
import java.util.Arrays;
import java.util.Random;
public class FirstOccurrence {
// Invariant: every index < lo holds a value < target,
// every index >= hi holds a value >= target.
// The window [lo, hi) is the only part not yet decided.
public static int firstOccurrence(int[] arr, int target) {
return firstOccurrence(arr, target, false);
}
static int firstOccurrence(int[] arr, int target, boolean trace) {
int lo = 0;
int hi = arr.length; // exclusive upper end
while (lo < hi) {
int mid = lo + (hi - lo) / 2; // no int overflow
if (trace) {
System.out.println(" lo=" + lo + " hi=" + hi + " mid=" + mid + " arr[mid]=" + arr[mid]);
}
if (arr[mid] < target) {
lo = mid + 1; // mid and everything left of it is too small
} else {
hi = mid; // mid could be the answer, keep it in the window
}
}
// lo == hi: the first index whose value is >= target
return (lo < arr.length && arr[lo] == target) ? lo : -1;
}
static int linearScan(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 2, 2, 2, 3, 5, 5, 8};
System.out.println("arr = " + Arrays.toString(arr));
System.out.println("target 2:");
System.out.println("result " + firstOccurrence(arr, 2, true));
System.out.println("target 4 (absent):");
System.out.println("result " + firstOccurrence(arr, 4, true));
System.out.println("empty array: " + firstOccurrence(new int[]{}, 7));
System.out.println("one element hit: " + firstOccurrence(new int[]{7}, 7));
System.out.println("one element miss: " + firstOccurrence(new int[]{7}, 3));
System.out.println("all equal: " + firstOccurrence(new int[]{4, 4, 4, 4, 4}, 4));
System.out.println("target at left end: " + firstOccurrence(arr, 1));
System.out.println("target at right end: " + firstOccurrence(arr, 8));
System.out.println("smaller than all: " + firstOccurrence(arr, 0));
System.out.println("larger than all: " + firstOccurrence(arr, 99));
Random rng = new Random(42);
for (int round = 0; round < 5000; round++) {
int[] a = new int[rng.nextInt(12)];
for (int i = 0; i < a.length; i++) a[i] = rng.nextInt(7);
Arrays.sort(a);
int t = rng.nextInt(9) - 1;
if (firstOccurrence(a, t) != linearScan(a, t)) {
throw new AssertionError(Arrays.toString(a) + " target " + t);
}
}
System.out.println("5000 random checks against a linear scan passed");
}
}
Run in an eclipse-temurin:21-jdk container, it prints:
arr = [1, 2, 2, 2, 2, 3, 5, 5, 8]
target 2:
lo=0 hi=9 mid=4 arr[mid]=2
lo=0 hi=4 mid=2 arr[mid]=2
lo=0 hi=2 mid=1 arr[mid]=2
lo=0 hi=1 mid=0 arr[mid]=1
result 1
target 4 (absent):
lo=0 hi=9 mid=4 arr[mid]=2
lo=5 hi=9 mid=7 arr[mid]=5
lo=5 hi=7 mid=6 arr[mid]=5
lo=5 hi=6 mid=5 arr[mid]=3
result -1
empty array: -1
one element hit: 0
one element miss: -1
all equal: 0
target at left end: 0
target at right end: 8
smaller than all: -1
larger than all: -1
5000 random checks against a linear scan passed
Worked trace
For target 2 in [1, 2, 2, 2, 2, 3, 5, 5, 8]: window [0, 9), mid 4 holds 2 (not smaller), so hi becomes 4. Window [0, 4), mid 2 holds 2, hi becomes 2. Window [0, 2), mid 1 holds 2, hi becomes 1. Window [0, 1), mid 0 holds 1 (smaller), so lo becomes 1. Now lo == hi == 1, arr[1] is 2, so the answer is 1 (the leftmost 2). For the absent target 4: mid 4 holds 2 (smaller), lo becomes 5; mid 7 holds 5, hi becomes 7; mid 6 holds 5, hi becomes 6; mid 5 holds 3 (smaller), lo becomes 6. Then lo == hi == 6, arr[6] is 5, which is not 4, so the method returns -1.
Complexity
Time O(log n): each round halves the window hi - lo, so at most about log2(n) + 1 rounds, plus one final array read. Space O(1). It is iterative, so there is no stack depth.
Edge cases and common mistakes
- Empty array: the window is empty, the final check fails the
lo < arr.lengthtest, and the method returns -1 (shown in the run). - One element: either the lone value matches (index 0) or it does not (-1).
- All-equal array: every
midsatisfiesarr[mid] >= target, sohikeeps moving left to 0 and the answer is 0, in O(log n). - Target absent, below the first element or above the last: the boundary lands at 0 or at
arr.length, and the final check returns -1 (the last case is whylo < arr.lengthmust come beforearr[lo], to avoid an out-of-bounds read). - Mistake:
hi = mid - 1on a match throws away a possible answer (whenmidis the first occurrence), and with a closed[lo, hi]window andhi = midthe loop can stop making progress; keep the window half-open and the update pairlo = mid + 1/hi = mid. - Mistake: returning immediately on
arr[mid] == target, which returns any occurrence rather than the first. - Mistake: forgetting the final equality check, which would return the boundary index for absent targets.
Running the code
Java 21 (JDK).
Save the listing as FirstOccurrence.java, then:
javac FirstOccurrence.java && java FirstOccurrence
Given a sorted array that may contain duplicates, implement in Java int[] searchRange(int[] nums, int target) that returns [firstIndex, lastIndex] if target is present or [-1, -1] otherwise. Use binary search variants to find leftmost and rightmost occurrences in O(log n) time. Show sample inputs (e.g., nums=[5,7,7,8,8,10], target=8 -> [3,4]) and discuss edge cases such as empty array or all-equal array.
Sample Answer
Direct answer
Run two boundary searches. The first finds the leftmost index with a value at least target (a lower bound); if that index is out of range or does not hold target, return [-1, -1]. The second finds the first index with a value strictly greater than target (an upper bound); the last occurrence is one before it. Each search is a binary search, so the total is O(log n) time and O(1) space, even when the array is all duplicates of the target.
The idea in plain words
With duplicates, "the" position of 8 in [5, 7, 7, 8, 8, 10] is a stretch of positions, 3 to 4. A normal binary search finds some index in that stretch and stops. We want both ends of the stretch. Because the array is sorted, the values go "smaller than 8", then "equal to 8", then "bigger than 8". The left end of the stretch is where "smaller" stops; the right end is where "bigger" begins, minus one. Each end is a boundary, and a boundary is exactly what a binary search with a small tweak finds.
Brute force and the tempting shortcut
A linear scan is O(n). A tempting shortcut is to binary search for any match and then walk left and right while the neighbours equal the target; that is O(log n + k), where k is the number of copies of the target. In an all-equal array every element is a copy, so k = n and the cost becomes O(n). The two boundary searches avoid the walk.
Approach and invariants
Both searches use a half-open window [lo, hi): the square bracket means index lo is inside the window and the round bracket means index hi is outside it, so [0, 6) covers indices 0 to 5. The window starts as [0, n) and lo can reach n (past the end), so an answer of n is reachable and the empty array needs no special case.
- Leftmost (
lowerBound): invariant, in words: everything left oflois smaller thantarget, everything fromhion is at leasttarget. Ifnums[mid] < targetsetlo = mid + 1, elsehi = mid(midmay be the answer, so it stays). - Past the rightmost (
upperBound): everything left oflois at mosttarget, everything fromhion is greater thantarget. Ifnums[mid] <= targetsetlo = mid + 1, elsehi = mid.
When lo == hi, that index is the boundary. searchRange calls lowerBound, checks the target is really there (first < n and nums[first] == target), and only then computes last = upperBound - 1. If the target is absent it returns [-1, -1] without the second search.
Code
The midpoint is lo + (hi - lo) / 2 so it cannot overflow int. The trace overloads print lo, hi and mid; the public method is the two-argument searchRange. main runs the sample from the question, the absent case, the edge cases and 5000 random sorted arrays (seed 11) against a linear scan.
import java.util.Arrays;
import java.util.Random;
public class SearchRange {
// First index with nums[i] >= target (nums.length if none).
// Invariant: nums[j] < target for j < lo, and nums[j] >= target for j >= hi.
static int lowerBound(int[] nums, int target, boolean trace) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (trace) System.out.println(" lower: lo=" + lo + " hi=" + hi + " mid=" + mid + " nums[mid]=" + nums[mid]);
if (nums[mid] < target) lo = mid + 1; else hi = mid;
}
return lo;
}
// First index with nums[i] > target (nums.length if none).
// Invariant: nums[j] <= target for j < lo, and nums[j] > target for j >= hi.
static int upperBound(int[] nums, int target, boolean trace) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (trace) System.out.println(" upper: lo=" + lo + " hi=" + hi + " mid=" + mid + " nums[mid]=" + nums[mid]);
if (nums[mid] <= target) lo = mid + 1; else hi = mid;
}
return lo;
}
public static int[] searchRange(int[] nums, int target) {
return searchRange(nums, target, false);
}
static int[] searchRange(int[] nums, int target, boolean trace) {
int first = lowerBound(nums, target, trace);
if (first == nums.length || nums[first] != target) {
return new int[]{-1, -1}; // target is absent
}
int last = upperBound(nums, target, trace) - 1;
return new int[]{first, last};
}
static int[] bruteForce(int[] nums, int target) {
int first = -1, last = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
if (first == -1) first = i;
last = i;
}
}
return new int[]{first, last};
}
public static void main(String[] args) {
int[] nums = {5, 7, 7, 8, 8, 10};
System.out.println("nums = " + Arrays.toString(nums) + ", target = 8");
System.out.println("result " + Arrays.toString(searchRange(nums, 8, true)));
System.out.println("target = 6 (absent):");
System.out.println("result " + Arrays.toString(searchRange(nums, 6, true)));
System.out.println("empty array: " + Arrays.toString(searchRange(new int[]{}, 0)));
System.out.println("one element hit: " + Arrays.toString(searchRange(new int[]{1}, 1)));
System.out.println("one element miss: " + Arrays.toString(searchRange(new int[]{1}, 2)));
System.out.println("all equal: " + Arrays.toString(searchRange(new int[]{2, 2, 2, 2}, 2)));
System.out.println("target at left end: " + Arrays.toString(searchRange(nums, 5)));
System.out.println("target at right end: " + Arrays.toString(searchRange(nums, 10)));
System.out.println("smaller than all: " + Arrays.toString(searchRange(nums, 1)));
System.out.println("larger than all: " + Arrays.toString(searchRange(nums, 50)));
Random rng = new Random(11);
for (int round = 0; round < 5000; round++) {
int[] a = new int[rng.nextInt(12)];
for (int i = 0; i < a.length; i++) a[i] = rng.nextInt(6);
Arrays.sort(a);
int t = rng.nextInt(8) - 1;
if (!Arrays.equals(searchRange(a, t), bruteForce(a, t))) {
throw new AssertionError(Arrays.toString(a) + " target " + t);
}
}
System.out.println("5000 random checks against a linear scan passed");
}
}
Run in an eclipse-temurin:21-jdk container, it prints:
nums = [5, 7, 7, 8, 8, 10], target = 8
lower: lo=0 hi=6 mid=3 nums[mid]=8
lower: lo=0 hi=3 mid=1 nums[mid]=7
lower: lo=2 hi=3 mid=2 nums[mid]=7
upper: lo=0 hi=6 mid=3 nums[mid]=8
upper: lo=4 hi=6 mid=5 nums[mid]=10
upper: lo=4 hi=5 mid=4 nums[mid]=8
result [3, 4]
target = 6 (absent):
lower: lo=0 hi=6 mid=3 nums[mid]=8
lower: lo=0 hi=3 mid=1 nums[mid]=7
lower: lo=0 hi=1 mid=0 nums[mid]=5
result [-1, -1]
empty array: [-1, -1]
one element hit: [0, 0]
one element miss: [-1, -1]
all equal: [0, 3]
target at left end: [0, 0]
target at right end: [5, 5]
smaller than all: [-1, -1]
larger than all: [-1, -1]
5000 random checks against a linear scan passed
Worked trace
For nums = [5, 7, 7, 8, 8, 10], target 8:
- Leftmost: window
[0, 6),mid3 holds 8 (not smaller),hibecomes 3. Window[0, 3),mid1 holds 7 (smaller),lobecomes 2. Window[2, 3),mid2 holds 7,lobecomes 3.lo == hi == 3, andnums[3]is 8, sofirstis 3. - Past the rightmost: window
[0, 6),mid3 holds 8 (not greater),lobecomes 4. Window[4, 6),mid5 holds 10 (greater),hibecomes 5. Window[4, 5),mid4 holds 8,lobecomes 5. The boundary is 5, solast = 5 - 1 = 4. - Result
[3, 4].
For the absent target 6, the leftmost search ends at index 1 (the first value at least 6 is the 7), nums[1] is not 6, so the result is [-1, -1].
The midpoint overflow, with numbers
A Java int holds values up to 2,147,483,647. If lo and hi are both large, lo + hi can pass that limit and wrap around to a negative number. This program uses two indexes near two billion:
public class MidpointOverflow {
public static void main(String[] args) {
int lo = 2_000_000_000, hi = 2_100_000_000;
System.out.println("int maximum: " + Integer.MAX_VALUE);
System.out.println("lo + hi as int: " + (lo + hi));
System.out.println("(lo + hi) / 2: " + ((lo + hi) / 2));
System.out.println("lo + (hi - lo) / 2: " + (lo + (hi - lo) / 2));
System.out.println("lo + hi as long: " + ((long) lo + hi));
}
}
Run in an eclipse-temurin:21-jdk container, it prints:
int maximum: 2147483647
lo + hi as int: -194967296
(lo + hi) / 2: -97483648
lo + (hi - lo) / 2: 2050000000
lo + hi as long: 4100000000
The true sum 4,100,000,000 does not fit in an int, so lo + hi wraps to -194967296, and (lo + hi) / 2 becomes a negative index. lo + (hi - lo) / 2 never forms the big sum: hi - lo is 100,000,000 and the result is 2,050,000,000, which is correct. Arrays that large are rare in practice, but the safe form costs nothing.
Complexity
Two binary searches, each O(log n): the window halves every round. Space O(1), iterative, no recursion. All-equal input does not change the cost, which is why this beats "find one match and expand".
Edge cases and common mistakes
- Empty array:
lowerBoundreturns 0 and0 == nums.length, so the result is[-1, -1](shown in the run). - One element:
[0, 0]for a hit,[-1, -1]for a miss. - All-equal array:
[2, 2, 2, 2]with target 2 returns[0, 3]. - Target at either end, or below or above everything: the run shows
[0, 0],[5, 5]and[-1, -1]for the last two. - Mistake: checking
nums[first]before checkingfirst < nums.lengththrowsArrayIndexOutOfBoundsExceptionwhen the target is bigger than everything. - Mistake: computing
lastasupperBoundwithout subtracting 1, or running the second search before knowing the target exists (harmless but wasted work). - Mistake:
hi = mid - 1in the boundary searches, which can skip the answer. - Mistake: unguarded
(lo + hi) / 2, which overflows a 32-bitintfor very large arrays (withlo= 2,000,000,000 andhi= 2,100,000,000 the sum wraps to a negative number, as the run above shows).
Running the code
Java 21 (JDK).
Save the listings as SearchRange.java and MidpointOverflow.java, then:
javac SearchRange.java && java SearchRange
javac MidpointOverflow.java && java MidpointOverflow
Given two sorted arrays, return one sorted array containing all elements. Then explain how the solution changes if the inputs are huge streams read one record at a time, and how to keep equal keys in input order.
Sample Answer
The idea in plain words
Both inputs are already sorted, so the smallest element left overall is always one of the two front elements. Keep one index in each array, compare the two front elements, copy the smaller to the output and advance that index. When one array runs out, copy the rest of the other (it is already sorted). Nothing has to be sorted again, which is why this is O(m + n) instead of the O((m + n) log (m + n)) of a general comparison sort that ignores the order already present.
This is the merge step of merge sort. Equal keys are handled by a rule, not by luck: when the fronts tie, take from the first input. That keeps the sort stable, meaning records with equal keys stay in the order they arrived (all of A's equals before B's).
Brute force
sorted(a + b) is correct, and it is also linear for two sorted inputs in practice, because Python's sort (Timsort) looks for stretches of the input that are already in order and merges those stretches instead of re-sorting them. What it cannot do is work on streams: it needs the whole data in memory, and it does not show the merge. The interviewer wants the two-pointer merge.
The code
merge_sorted handles lists, an optional key, and descending order. merge_streams is the version for inputs read one record at a time. It is a generator: a function that contains yield, which hands back one value and then pauses until the caller asks for the next one, so the merged output is produced lazily and only the current front record of each stream is held in memory. next(it, sentinel) asks an iterator for its next item and returns sentinel (a unique object() that no real record can equal) when the stream is exhausted, which is how the code tells "stream finished" apart from any real value. parse_lines uses str.partition(","), which splits a line at the first comma into the text before it, the comma itself (empty if there is none) and the text after it. parse_lines turns text lines like 4,bravo into records and skips and counts malformed lines. merge_halves merges two adjacent sorted parts of one array, copying only the left part out.
import io
import random
import re
KEY = re.compile(r"-?[0-9]+") # optional minus sign, then ASCII digits only
def merge_sorted(a, b, key=lambda x: x, reverse=False):
"""Merge two sorted lists into a new list. On equal keys the item from `a`
comes first, so records from the first input keep priority."""
out = []
i = j = 0
comparisons = 0
while i < len(a) and j < len(b):
comparisons += 1
ka, kb = key(a[i]), key(b[j])
take_a = ka >= kb if reverse else ka <= kb # <= (or >=) is what makes ties stable
if take_a:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
out.extend(a[i:]) # at most one of these two is non-empty
out.extend(b[j:])
return out, comparisons
def merge_streams(stream_a, stream_b, key=lambda x: x):
"""Generator version: holds only the current head of each stream."""
it_a, it_b = iter(stream_a), iter(stream_b)
sentinel = object()
head_a, head_b = next(it_a, sentinel), next(it_b, sentinel)
while head_a is not sentinel and head_b is not sentinel:
if key(head_a) <= key(head_b):
yield head_a
head_a = next(it_a, sentinel)
else:
yield head_b
head_b = next(it_b, sentinel)
while head_a is not sentinel:
yield head_a
head_a = next(it_a, sentinel)
while head_b is not sentinel:
yield head_b
head_b = next(it_b, sentinel)
def parse_lines(lines, source, bad):
"""Turn 'key,payload' lines into (key, payload, source); skip and count bad lines."""
for line in lines:
key_text, sep, payload = line.strip().partition(",")
if not sep or not KEY.fullmatch(key_text):
bad[source] += 1
continue
yield int(key_text), payload, source
def merge_halves(arr, lo, mid, hi):
"""Merge sorted arr[lo:mid] and arr[mid:hi] inside one array; only the left half is copied."""
left = arr[lo:mid]
i, j, k = 0, mid, lo
while i < len(left) and j < hi:
if arr[j] < left[i]:
arr[k] = arr[j]
j += 1
else:
arr[k] = left[i]
i += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
if __name__ == "__main__":
a, b = [1, 4, 4, 9], [2, 4, 7, 10, 11]
merged, comps = merge_sorted(a, b)
print(merged, f"comparisons: {comps} (at most {len(a) + len(b) - 1})")
print(merge_sorted([], [3, 5])[0], merge_sorted([2], [])[0], merge_sorted([], [])[0])
# Stability with tagged equal keys: (key, source).
pa = [(1, "A0"), (4, "A1"), (4, "A2")]
pb = [(4, "B0"), (4, "B1"), (5, "B2")]
print([t[1] for t in merge_sorted(pa, pb, key=lambda r: r[0])[0]])
# Descending by key, still stable: ties keep A before B.
da = [(9, "A0"), (4, "A1"), (4, "A2")]
db = [(7, "B0"), (4, "B1"), (1, "B2")]
print([t[1] for t in merge_sorted(da, db, key=lambda r: r[0], reverse=True)[0]])
# Streams of text lines, one record at a time, with malformed lines skipped.
file_a = io.StringIO("1,alpha\n4,bravo\noops\n4,charlie\n9,delta\n")
file_b = io.StringIO("2,echo\n4,foxtrot\n,missing key\n5,golf\n")
bad = {"A": 0, "B": 0}
merged_stream = merge_streams(parse_lines(file_a, "A", bad), parse_lines(file_b, "B", bad),
key=lambda r: r[0])
for key, payload, source in merged_stream:
print(f" {key} {payload} (from {source})")
print("malformed lines skipped:", bad)
odd = {"C": 0}
print(list(parse_lines(["--5,x", "²,x", "-7,ok"], "C", odd)), odd)
# Two adjacent sorted halves of one array.
arr = [3, 8, 8, 12, 1, 8, 9]
merge_halves(arr, 0, 4, 7)
print("halves merged in one array:", arr)
# Check against sorted() on random sorted inputs, tagged so ties are visible.
rnd = random.Random(11)
for _ in range(500):
x = sorted((rnd.randint(0, 5), "x", i) for i in range(rnd.randint(0, 8)))
y = sorted((rnd.randint(0, 5), "y", i) for i in range(rnd.randint(0, 8)))
x = sorted(x, key=lambda r: r[0])
y = sorted(y, key=lambda r: r[0])
expect = sorted(x + y, key=lambda r: r[0]) # stable sort of the concatenation
assert merge_sorted(x, y, key=lambda r: r[0])[0] == expect
assert list(merge_streams(x, y, key=lambda r: r[0])) == expect
print("500 random pairs match a stable sort of the concatenation: ok")
Run in a python:3.12 container (Python 3.12), it prints:
[1, 2, 4, 4, 4, 7, 9, 10, 11] comparisons: 7 (at most 8)
[3, 5] [2] []
['A0', 'A1', 'A2', 'B0', 'B1', 'B2']
['A0', 'B0', 'A1', 'A2', 'B1', 'B2']
1 alpha (from A)
2 echo (from B)
4 bravo (from A)
4 charlie (from A)
4 foxtrot (from B)
5 golf (from B)
9 delta (from A)
malformed lines skipped: {'A': 1, 'B': 1}
[(-7, 'ok', 'C')] {'C': 2}
halves merged in one array: [1, 3, 8, 8, 8, 9, 12]
500 random pairs match a stable sort of the concatenation: ok
Reading the output
- The first line merges
[1, 4, 4, 9]and[2, 4, 7, 10, 11]. It used 7 comparisons against an upper bound of m + n - 1 = 8: once A ran out, the rest of B (10 and 11) was copied without comparing. The second line shows the empty cases: one side empty returns a copy of the other, and both empty returns[]. - The tag list shows stability: records with key 4 come out as
A1, A2, B0, B1, A's before B's, each group in its own input order (the key-5 and key-1 records fall where their keys put them). - The descending run uses
>=instead of<=for the same reason. Keys 9, 7, 4, 4, 4, 1 giveA0, B0, A1, A2, B1, B2, so A's tied 4s still come before B's. - The streaming run merges two text sources. Source A holds
1,alpha,4,bravo,oops,4,charlie,9,delta, so it has 4 valid records (keys 1, 4, 4, 9) and one malformed line. Source B holds2,echo,4,foxtrot,,missing key,5,golf, so it has 3 valid records (keys 2, 4, 5) and one malformed line (empty key). The linesoopsand,missing keyare skipped and counted, and the output is all seven valid records (4 + 3) in key order. The three records with key 4 come out asbravo,charlie(both from A) and thenfoxtrot(from B), because A wins ties. The next line feeds three more lines throughparse_lines:--5,x(two minus signs) and²,x(a superscript two) are both rejected and counted, and only-7,okbecomes a record. The key test is a regular expression for an optional minus sign followed by ASCII digits becausestr.isdigit()accepts characters such as²thatint()then refuses, which would crash the reader instead of counting the line. merge_halvesturns[3, 8, 8, 12 | 1, 8, 9]into one sorted array.
Complexity
- Time: O(m + n). Each loop step advances one index, and there are m + n elements in total. At most m + n - 1 comparisons.
- Space:
merge_sortedreturns a new list, so O(m + n) output (the input is not modified).merge_streamsuses O(1) extra memory: two current records, no matter how large the inputs are.merge_halvesuses O(left length) extra, which is the O(n) auxiliary buffer that merge sort pays. - The driver checks 500 random pairs (including empty ones) against a stable sort of the concatenation, with tagged equal keys, for both the list and the generator version.
If the inputs are huge streams
- Read one record from each source, compare, yield the smaller and refill only that source. Nothing is stored, so memory is constant and the output can be written to disk or sent on as it is produced.
- Malformed lines: validate in the reader (
parse_lines), skip bad ones, and keep a counter so data loss is visible instead of silent. A bad line must not reach the comparison. - Unsorted input is not detected by the merge. If a stream is out of order the output is out of order without any error. When the sources are not trusted, remember the previous key from each stream and raise (or count) when a key goes backwards.
- Ties across sources: decide a priority (A before B) and apply it with
<=; that is also what makes the result match a stable sort of A followed by B. - To merge many streams rather than two (a k-way merge, k being the number of streams), keep the current front record of every stream in a heap and repeatedly pop the smallest, then refill from the stream it came from. For two streams the plain comparison above is the same idea with k = 2; interviews usually ask for the two-stream version and mention the heap for k streams.
Edge cases and common mistakes
- Either input empty, both empty, one input entirely before the other, all keys equal.
- Forgetting the leftover copy after the loop drops the tail of the longer array.
<instead of<=on the tie takes B's record first, so tied records from the two inputs swap priority (B's before A's, each input's own order kept).- Using
a.pop(0)for the front element makes each step O(n) and the whole merge O(n^2) for lists; indices are O(1). - Descending merges need the opposite comparison; sorting with
reverse=Trueafterwards would throw away the sorted inputs.
Running the code
Save the program as merge_two_sorted.py and run:
python merge_two_sorted.py
Standard library only (io, random); no install or config needed.
List common off-by-one mistakes and mid-calculation errors that cause binary search implementations to loop infinitely or return incorrect indices. For each mistake give a short example input that breaks the incorrect implementation and explain the root cause.
Sample Answer
The idea in plain words
A binary search is a loop that keeps a window [lo, hi] of positions where the target could still be, and shrinks it using the middle element. Almost every bug is a mismatch between three choices that must agree: what the window means (does hi point at a real candidate, or one past the end?), when the loop stops (lo <= hi or lo < hi), and how the window shrinks (mid + 1, mid - 1, or mid). A mismatch skips a candidate, or leaves the window the same size so the loop never ends.
The correct closed-window version has this invariant, in words: if the target is in the list, it is somewhere in a[lo..hi], both ends included. The loop runs while the window is non-empty (lo <= hi), and each step removes mid from the window, so it must shrink.
The programs
Buggy functions 1 to 5 below each change one thing from correct; 6 and 7 are first-occurrence and last-occurrence searches with one thing wrong. To make an endless loop visible instead of hanging the program, the runner passes a list subclass that raises an error after 100 reads (Looping); a correct search on these tiny lists never gets near that. In Guarded, the method __getitem__ is what Python calls for every a[i], so each read adds one to reads, and super().__getitem__(i) then does the ordinary list read. The block that prints the int32 line runs the midpoint formula over a virtual sorted array of two billion items (nothing is stored: the value at index i is just i), with a function that wraps the sum the way a signed 32-bit integer does.
import itertools
class Looping(Exception):
pass
class Guarded(list):
"""A list that raises Looping after too many reads, so an infinite loop shows up as an error."""
reads = 0
def __getitem__(self, i):
self.reads += 1
if self.reads > 100:
raise Looping("more than 100 reads")
return super().__getitem__(i)
def correct(a, t): # closed window [lo, hi]; invariant: t, if present, is in a[lo..hi]
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_strict_loop(a, t): # 1. 'lo < hi' with a closed window
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_lo_equals_mid(a, t): # 2. 'lo = mid' never shrinks the window
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid
else:
hi = mid - 1
return -1
def bug_hi_equals_mid(a, t): # 3. 'hi = mid' with a closed window
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid
return -1
def bug_hi_is_len(a, t): # 4. hi = len(a) but the loop treats hi as inclusive
lo, hi = 0, len(a)
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_float_mid(a, t): # 5. '/' instead of '//' in Python 3
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) / 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def first_ge(a, t): # reference: first index with a[i] >= t
return next((i for i, x in enumerate(a) if x >= t), len(a))
def bug_first_occurrence(a, t): # 6. half-open window but 'hi = mid - 1'
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] >= t:
hi = mid - 1
else:
lo = mid + 1
return lo
def last_le(a, t): # reference: last index with a[i] <= t, or -1
return max((i for i, x in enumerate(a) if x <= t), default=-1)
def bug_last_occurrence(a, t): # 7. 'lo = mid' needs the upper middle, but mid rounds down
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] <= t:
lo = mid
else:
hi = mid - 1
return lo if a and a[lo] <= t else -1
def first_ge_fixed(a, t): # half-open window: hi = mid keeps a possible answer
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] >= t:
hi = mid
else:
lo = mid + 1
return lo
def last_le_fixed(a, t): # closed window, 'lo = mid' paired with the upper middle
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if a[mid] <= t:
lo = mid
else:
hi = mid - 1
return lo if a and a[lo] <= t else -1
def run(fn, a, t):
try:
return fn(Guarded(a), t)
except Looping:
return "infinite loop"
except Exception as e:
return type(e).__name__
def to_int32(x):
x &= 0xFFFFFFFF
return x - (1 << 32) if x >= (1 << 31) else x
def search_virtual(n, target, midpoint):
"""Binary search over the virtual sorted array [0, 1, ..., n-1]."""
lo, hi = 0, n - 1
steps = []
while lo <= hi:
mid = midpoint(lo, hi)
steps.append((lo, hi, mid))
if mid < 0:
return "negative index " + str(mid), steps
if mid == target:
return mid, steps
if mid < target:
lo = mid + 1
else:
hi = mid - 1
return -1, steps
cases = [
("1 strict loop ", bug_strict_loop, [1, 3, 5], 5),
("1 strict loop ", bug_strict_loop, [4], 4),
("2 lo = mid ", bug_lo_equals_mid, [1, 3], 3),
("3 hi = mid ", bug_hi_equals_mid, [1, 3], 0),
("4 hi = len(a) ", bug_hi_is_len, [1, 3, 5], 9),
("5 mid = (lo+hi)/2 ", bug_float_mid, [1, 3, 5], 3),
]
for name, fn, a, t in cases:
print(f"{name} a={a} target={t}: buggy={run(fn, a, t)} correct={correct(a, t)}")
for name, fn, ref, a, t in [
("6 first, hi=mid-1 ", bug_first_occurrence, first_ge, [1, 2, 3, 3], 3),
("7 last, lo=mid ", bug_last_occurrence, last_le, [1, 2], 2),
]:
print(f"{name} a={a} target={t}: buggy={run(fn, a, t)} correct={ref(a, t)}")
# Every non-decreasing list of length 0..5 over the values 0..3, with targets -1..4.
inputs = [(list(c), t) for n in range(6)
for c in itertools.combinations_with_replacement(range(4), n) for t in range(-1, 5)]
print("\ninputs per check:", len(inputs))
def fails(fn, expect):
bad = 0
for a, t in inputs:
got = run(fn, a, t)
bad += got != expect(a, t)
return bad
for name, fn in [("correct", correct), ("bug 1", bug_strict_loop), ("bug 2", bug_lo_equals_mid),
("bug 3", bug_hi_equals_mid), ("bug 4", bug_hi_is_len), ("bug 5", bug_float_mid)]:
bad = 0
for a, t in inputs:
got = run(fn, a, t)
ok = isinstance(got, int) and ((got == -1 and t not in a) or (got != -1 and a[got] == t))
bad += not ok
print(f"{name:8} wrong or crashing on {bad} inputs")
print("bug 6 wrong on", fails(bug_first_occurrence, first_ge), "inputs")
print("bug 7 wrong on", fails(bug_last_occurrence, last_le), "inputs")
print("fixed 6 wrong on", fails(first_ge_fixed, first_ge), "inputs")
print("fixed 7 wrong on", fails(last_le_fixed, last_le), "inputs")
print()
n = 2_000_000_000
total = 1_000_000_000 + 1_999_999_999
print(f"int32 maximum 2,147,483,647; sum {total:,} wraps to {to_int32(total):,} "
f"(= {total:,} - 2**32), halved with // gives {to_int32(total) // 2:,}")
for label, mid in [("(lo+hi)//2 in int32", lambda lo, hi: to_int32(lo + hi) // 2),
("lo+(hi-lo)//2 ", lambda lo, hi: lo + (hi - lo) // 2)]:
result, steps = search_virtual(n, n - 1, mid)
print(f"{label}: result={result} after {len(steps)} steps; last (lo, hi, mid) = {steps[-1]}")
print()
a, t = [1, 3, 5, 7], 4
lo, hi = 0, len(a) - 1
print(f"correct search for {t} in {a}:")
while lo <= hi:
mid = lo + (hi - lo) // 2
print(f" lo={lo} hi={hi} mid={mid} a[mid]={a[mid]}")
if a[mid] == t:
break
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
print(f" ends with lo={lo} hi={hi}: empty window, return -1")
The output below is the complete output of that program.
1 strict loop a=[1, 3, 5] target=5: buggy=-1 correct=2
1 strict loop a=[4] target=4: buggy=-1 correct=0
2 lo = mid a=[1, 3] target=3: buggy=infinite loop correct=1
3 hi = mid a=[1, 3] target=0: buggy=infinite loop correct=-1
4 hi = len(a) a=[1, 3, 5] target=9: buggy=IndexError correct=-1
5 mid = (lo+hi)/2 a=[1, 3, 5] target=3: buggy=TypeError correct=1
6 first, hi=mid-1 a=[1, 2, 3, 3] target=3: buggy=1 correct=2
7 last, lo=mid a=[1, 2] target=2: buggy=infinite loop correct=1
inputs per check: 756
correct wrong or crashing on 0 inputs
bug 1 wrong or crashing on 87 inputs
bug 2 wrong or crashing on 323 inputs
bug 3 wrong or crashing on 265 inputs
bug 4 wrong or crashing on 211 inputs
bug 5 wrong or crashing on 750 inputs
bug 6 wrong on 102 inputs
bug 7 wrong on 446 inputs
fixed 6 wrong on 0 inputs
fixed 7 wrong on 0 inputs
int32 maximum 2,147,483,647; sum 2,999,999,999 wraps to -1,294,967,297 (= 2,999,999,999 - 2**32), halved with // gives -647,483,649
(lo+hi)//2 in int32: result=negative index -647483649 after 2 steps; last (lo, hi, mid) = (1000000000, 1999999999, -647483649)
lo+(hi-lo)//2 : result=1999999999 after 31 steps; last (lo, hi, mid) = (1999999999, 1999999999, 1999999999)
correct search for 4 in [1, 3, 5, 7]:
lo=0 hi=3 mid=1 a[mid]=3
lo=2 hi=3 mid=2 a[mid]=5
ends with lo=2 hi=1: empty window, return -1
The eight mistakes, each with its failing input and cause
- Loop condition
lo < hiwith a closed window. On[1, 3, 5], target 5, the window shrinks tolo=hi=2and the loop exits without ever looking at index 2, so the result is -1 instead of 2.[4]with target 4 fails the same way: the loop never starts. Root cause: withhia real candidate, a window of size one is still unsearched. Fix:lo <= hi. lo = midinstead ofmid + 1. On[1, 3], target 3:mid=0,a[0]=1 < 3, andlois set back to 0, so the window never changes. The guard reports an infinite loop. Root cause:midwas already inspected and rejected, so it must leave the window. Fix:lo = mid + 1.hi = midinstead ofmid - 1. On[1, 3], target 0:mid=0,a[0]=1 > 0,hi=0, and the next round repeats exactly. Same root cause as mistake 2, on the other side.hi = len(a)with an inclusive loop. On[1, 3, 5], target 9 the window reacheshi=3,mid=3, anda[3]raisesIndexError. Root cause: the code mixes the half-open convention (hiis one past the end) with the closed-window loop (lo <= hireadsa[hi]). Pick one convention and keep every line consistent with it./instead of//for the midpoint. In Python 3,(lo + hi) / 2is a float:a[1.0]raisesTypeErroron[1, 3, 5](every input with a non-empty list that reaches a probe, which is why 750 of 756 inputs fail). Habits from C and Java, where/on two integers gives an integer, cause this; use//.- First-occurrence search over a half-open window (
hi = len(a), looplo < hi) that setshi = mid - 1. On[1, 2, 3, 3], target 3 the buggy search returns 1, but the first index with a value >= 3 is 2. Root cause: for "first index that satisfies a condition",miditself may be the answer when the condition holds, so it must stay:hi = mid. Throwing it away silently skips the answer. The working form isfirst_ge_fixedin the listing:if a[mid] >= t: hi = mid, elselo = mid + 1, which fails on 0 of the 756 inputs. lo = midwhile searching for the last occurrence, withmidrounding down. On[1, 2], target 2:lo=0, hi=1, mid=0, the condition holds,lo = mid = 0again, and the window never shrinks. Root cause: when the update keepsmid(lo = mid), the midpoint must round up (the upper middle: for a window of two items, the right one) so it differs fromlo:mid = lo + (hi - lo + 1) // 2. The mirror rule: updates that keepmidon thehiside use the rounded-down midpoint. The working form islast_le_fixedin the listing, which also fails on 0 of the 756 inputs.- Midpoint overflow,
(lo + hi) // 2in a 32-bit signed integer. The last block searches the virtual array0..1,999,999,999for the value 1,999,999,999. A signed 32-bit integer holds values only up to 2,147,483,647. In Java a sum past that is defined to wrap around by 2^32 = 4,294,967,296 (in C and C++ signed overflow is itself undefined behaviour, and on common hardware it typically wraps the same way); the program emulates the wrapping. The first probe is safe (0 + 1,999,999,999 fits), and the search moves tolo=1,000,000,000andhi=1,999,999,999. Then the sum 2,999,999,999 is above the limit, so it wraps to 2,999,999,999 - 4,294,967,296 = -1,294,967,297, and the program's floor division gives -647,483,649 (both numbers are on the int32 line of the output, and the line after it prints the failing search): a negative index. Integer division in Java, C and C++ truncates toward zero instead of flooring, so(lo + hi) / 2there gives -647,483,648 for this sum (run in an eclipse-temurin:21-jdk container); either way the index is negative. In C and C++ an out-of-range read is undefined behaviour, meaning the language puts no requirement on what happens, so the program may crash or read garbage; other languages raise an exception or return the wrong element. Withlo + (hi - lo) // 2the same search ends at the right index after 31 steps. Python's integers never overflow, so this only appears in fixed-width languages or when you emulate them as above.
The counts after "inputs per check" come from running each version on all 756 non-decreasing lists of length 0 to 5 over the values 0 to 3, with every target from -1 to 4: the correct version fails on 0, and every buggy version fails on a different number of inputs. Mistake 6 and 7 are judged against a first-index-at-or-above and last-index-at-or-below reference, the others against "an index holding the target, or -1".
The correct version, step by step
The final block traces the correct search for the absent value 4 in [1, 3, 5, 7]: probe index 1 (value 3, too small) so lo=2; probe index 2 (value 5, too big) so hi=1. Now lo=2 > hi=1, the window is empty, and the function returns -1. The loop ends exactly when the window empties, which is why lo <= hi is the matching condition for a closed window.
A rule to keep
Choose a convention before writing any line, and check three things against it: the initial hi, the loop condition, and each update. Then run three inputs on a one-element list [4]: target 4 (a hit), target 0 (below everything) and target 9 (above everything). Those catch mistakes 1 to 4 immediately.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python binary_search_bugs.py
Save the program as binary_search_bugs.py. It uses only the standard library, and the output above is from Python 3.12.
Unlock Full Question Bank
Get access to all 14 Sorting and Searching Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.