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.
Formalize and prove binary search correctness using loop invariants for both inclusive [low,high] and exclusive [low,high) variants. State the invariant precisely, prove initialization, maintenance and termination conditions, and show how computing mid as low + (high - low)/2 prevents integer overflow in languages with fixed-width integers. Provide a termination argument based on interval shrinking.
Sample Answer
The idea in plain words
Binary search looks for a target in a sorted array by keeping a window of indices that could still hold it and throwing away half of the window each step. A loop invariant is a statement about the variables that is true before the loop starts and stays true after every pass. If you can prove the invariant, and prove the loop must stop, then the state when the loop stops is a correct answer. The proof has three parts: initialization (true before the first pass), maintenance (if true before a pass, true after it) and termination (the loop ends, and invariant plus exit condition give the answer).
The window can be written two ways. Closed [lo, hi] includes both ends and the loop runs while lo <= hi. Half-open [lo, hi) includes lo but excludes hi, so the empty window is lo == hi and the loop runs while lo < hi. The two are not interchangeable line by line: the update rules differ (hi = mid - 1 versus hi = mid), and mixing them is the classic bug shown at the end.
Invariants
In words: everything left of the window is too small and everything right of it is too large, so if the target exists at all, it is inside the window. The table says exactly that in symbols. Let a be sorted in non-decreasing order (each element is at least the one before it; equal neighbours are allowed) with n elements, and let target be the value sought. Python's // is floor division: it rounds down to a whole number, so 7 // 2 is 3.
| Convention | Initial window | Loop condition | Invariant |
|---|---|---|---|
| Closed | lo = 0, hi = n - 1 | lo <= hi | every index i < lo has a[i] < target, and every index i > hi has a[i] > target |
| Half-open | lo = 0, hi = n | lo < hi | every index i < lo has a[i] < target, and every index i >= hi has a[i] > target |
Proof for the closed variant
Initialization. With lo = 0 there is no index i < 0, and with hi = n - 1 there is no index i > n - 1. Both conditions hold vacuously: a claim of the form "every index in this set has property P" is true when the set is empty, because there is nothing that could break it.
Maintenance. The body runs only when lo <= hi. Then mid = lo + (hi - lo) // 2 satisfies lo <= mid <= hi, because 0 <= (hi - lo) // 2 <= hi - lo, so a[mid] is a valid read. Three cases:
a[mid] == target: returnmid, which is correct.a[mid] < target: for everyi <= mid, sortedness givesa[i] <= a[mid] < target. Settinglo = mid + 1keeps "everything left oflois smaller" true.hiis unchanged, so the right-hand half of the invariant is untouched.a[mid] > target: for everyi >= mid,a[i] >= a[mid] > target. Settinghi = mid - 1keeps "everything right ofhiis larger" true.
Termination. Let s = hi - lo + 1 be the number of indices in the window, a non-negative integer. After one pass the new size s' satisfies s' <= s // 2: going left gives s' = (mid - 1) - lo + 1 = (s - 1) // 2, and going right gives s' = hi - (mid + 1) + 1 = s - 1 - (s - 1) // 2 = s // 2. Check with numbers (printed by the program): for s = 5, mid is the third index, so both sides keep 2 indices and 5 // 2 is 2; for s = 4, going left keeps 1 index and going right keeps 2, and 4 // 2 is 2. Since s is a strictly decreasing non-negative integer, the loop must exit. Neither update can skip past the other end (lo becomes at most hi + 1, and hi at least lo - 1), so the exit state is exactly lo == hi + 1.
Conclusion. At exit the invariant says every index below lo is smaller and every index above hi = lo - 1, that is every index >= lo, is larger. No index holds the target, so returning -1 is correct. As a bonus, lo is the insertion point: the position where target could be inserted and keep the array sorted (the same index Python's bisect_left returns).
Proof for the half-open variant
Initialization. lo = 0 and hi = n leave no index below lo and no index at or above n: vacuous again.
Maintenance. The body runs when lo < hi, so the window size s = hi - lo >= 1. Then mid = lo + s // 2 satisfies lo <= mid <= hi - 1 (for s = 1, mid = lo; for s = 2, mid = lo + 1 = hi - 1; in general s // 2 <= s - 1 whenever s >= 1), so a[mid] is valid. If a[mid] < target, every i <= mid is smaller, so lo = mid + 1 is safe. If a[mid] > target, every i >= mid is larger, and hi = mid is safe: hi is exclusive, so mid itself is excluded, which is exactly why no - 1 appears here.
Termination. Going left gives s' = mid - lo = s // 2. Going right gives s' = hi - (mid + 1) = s - s // 2 - 1, which is at most s // 2 (for s = 5 both are 2, for s = 4 the right side keeps 1 and the left side 2, as the printed sizes show). So again s' <= s // 2 and the loop exits with lo == hi.
Conclusion. At exit everything below lo is smaller and everything at or above hi = lo is larger, so the target is absent and lo is the insertion point.
Termination argument from interval shrinking
Because s' <= s // 2 in both variants, after k passes the window has at most n // 2**k elements. The window is empty once 2**k > n, so the number of passes is at most n.bit_length() (the number of binary digits needed to write n: 5 is 101, so 3), which equals floor(log2 n) + 1 for n >= 1 and 0 for n = 0. For n = 0, 1 and 2 the bound is 0, 1 and 2 passes. The run below confirms the bound is tight: for every length from 0 to 8 tested, the worst case equals it exactly.
Midpoint overflow
(lo + hi) // 2 computes the sum first. In a fixed-width signed 32-bit type the largest value is 2147483647. With lo = 1500000000 and hi = 2000000000 the true sum is 3500000000, which does not fit. In Java the spec says integer operators "do not indicate overflow or underflow in any way": the sum wraps around to a negative number (two's complement is how signed integers are stored in 32 bits; a result above 2147483647 comes back as the true value minus 232, and the output shows 3500000000 - 4294967296 = -794967296), and the midpoint index is negative. In C and C++ the operands are int, so signed overflow is undefined behaviour: the language standard places no requirement on what happens, so the program may produce garbage, crash, or appear to work. lo + (hi - lo) // 2 never leaves the range: hi - lo is between 0 and n - 1, and the result is at most hi, so every intermediate value is a valid index. The unsafe form only fails on arrays longer than about 230 (1.07 billion) elements, so it hides in tests. Python integers have no fixed width, so the program below emulates 32 bits with to_int32. The same sums in Java, where int is 32 bits wide (JDK 21, saved as MidpointOverflow.java):
public class MidpointOverflow {
public static void main(String[] args) {
int lo = 1_500_000_000, hi = 2_000_000_000;
System.out.println("lo + hi = " + (lo + hi));
System.out.println("(lo + hi) / 2 = " + ((lo + hi) / 2));
System.out.println("(lo + hi) >>> 1 = " + ((lo + hi) >>> 1));
System.out.println("lo + (hi - lo)/2 = " + (lo + (hi - lo) / 2));
}
}
lo + hi = -794967296
(lo + hi) / 2 = -397483648
(lo + hi) >>> 1 = 1750000000
lo + (hi - lo)/2 = 1750000000
The unsigned shift >>> 1 is another safe midpoint in Java, because it treats the wrapped sum as an unsigned 32-bit number; it only works while the true sum stays below 2**32. In languages without that operator, use lo + (hi - lo) / 2.
Code, traces and exhaustive check
The functions assert the invariant on every pass (instrumentation), print a lo / mid / hi trace for a hit, a miss and an empty array, then check both variants against every non-decreasing array of length 0 to 7 over the values 0 to 3 and every target from -1 to 4.
from bisect import bisect_left
from itertools import combinations_with_replacement
def invariant_closed(a, target, lo, hi):
# every index left of lo holds a smaller value, every index right of hi a larger one
return all(a[i] < target for i in range(lo)) and all(a[i] > target for i in range(hi + 1, len(a)))
def invariant_half_open(a, target, lo, hi):
return all(a[i] < target for i in range(lo)) and all(a[i] > target for i in range(hi, len(a)))
def search_closed(a, target, trace=None):
"""Closed interval [lo, hi]. Returns (index or -1, lo at exit, loop iterations)."""
lo, hi = 0, len(a) - 1
steps = 0
while lo <= hi:
assert invariant_closed(a, target, lo, hi)
mid = lo + (hi - lo) // 2
steps += 1
if trace is not None:
trace.append(f"lo={lo} mid={mid} hi={hi} a[mid]={a[mid]}")
if a[mid] == target:
return mid, lo, steps
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
assert invariant_closed(a, target, lo, hi) and lo == hi + 1
if trace is not None:
trace.append(f"lo={lo} hi={hi} -> interval empty")
return -1, lo, steps
def search_half_open(a, target, trace=None):
"""Half-open interval [lo, hi). Returns (index or -1, lo at exit, loop iterations)."""
lo, hi = 0, len(a)
steps = 0
while lo < hi:
assert invariant_half_open(a, target, lo, hi)
mid = lo + (hi - lo) // 2
steps += 1
if trace is not None:
trace.append(f"lo={lo} mid={mid} hi={hi} a[mid]={a[mid]}")
if a[mid] == target:
return mid, lo, steps
if a[mid] < target:
lo = mid + 1
else:
hi = mid
assert invariant_half_open(a, target, lo, hi) and lo == hi
if trace is not None:
trace.append(f"lo={lo} hi={hi} -> interval empty")
return -1, lo, steps
def show(name, fn, a, target):
trace = []
result = fn(a, target, trace)
print(f"{name}: a={a} target={target} -> index {result[0]}")
for line in trace:
print(" ", line)
show("closed ", search_closed, [1, 3, 5, 7, 9], 7)
show("half-open", search_half_open, [1, 3, 5, 7, 9], 7)
show("closed ", search_closed, [1, 3, 5, 7, 9], 4)
show("half-open", search_half_open, [1, 3, 5, 7, 9], 4)
show("closed ", search_closed, [], 5)
show("half-open", search_half_open, [], 5)
# Exhaustive check: every non-decreasing array of length 0..7 over values 0..3, every target -1..4.
cases = worst = 0
for n in range(8):
for a in map(list, combinations_with_replacement(range(4), n)):
for target in range(-1, 5):
for fn in (search_closed, search_half_open):
index, lo, steps = fn(a, target)
if target in a:
assert index != -1 and a[index] == target
else:
assert index == -1 and lo == bisect_left(a, target)
assert steps <= n.bit_length()
worst = max(worst, steps - n.bit_length())
cases += 1
print("exhaustive cases checked:", cases, "| max (steps - bit_length(n)):", worst)
# Termination: size of the candidate interval at least halves each pass.
for n in range(0, 9):
print("n =", n, "bound n.bit_length() =", n.bit_length(), end=" | ")
print("measured worst:", max((search_closed(list(range(n)), t)[2] for t in range(-1, n + 1)), default=0))
# One pass, by numbers: window sizes after the midpoint probe, for three starting sizes.
for s in (4, 5, 6):
lo, hi = 0, s - 1
mid = lo + (hi - lo) // 2
hmid = s // 2 # half-open window [0, s): mid = lo + s // 2
print(f"s={s}: closed -> left {mid - lo}, right {hi - mid} | half-open -> left {hmid}, right {s - hmid - 1} | s // 2 = {s // 2}")
# 32-bit overflow of the midpoint, emulated by wrapping to a signed 32-bit integer.
def to_int32(x):
x &= 0xFFFFFFFF
return x - (1 << 32) if x & 0x80000000 else x
lo, hi = 1_500_000_000, 2_000_000_000
print("int32 max:", 2**31 - 1)
print("true sum:", lo + hi, "| minus 2**32 =", lo + hi - 2**32, "(the wrap-around subtracts 2**32 from a sum above int32 max)")
print("lo + hi wrapped:", to_int32(lo + hi), "-> (lo + hi) / 2 =", int(to_int32(lo + hi) / 2))
print("lo + (hi - lo) / 2 =", lo + (hi - lo) // 2)
# Mixing the two conventions: half-open start with a closed-interval update.
def mixed(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print("mixed conventions on [1, 3, 5, 7] searching 3:", mixed([1, 3, 5, 7], 3))
print("half-open on [1, 3, 5, 7] searching 3:", search_half_open([1, 3, 5, 7], 3)[0])
Output:
closed : a=[1, 3, 5, 7, 9] target=7 -> index 3
lo=0 mid=2 hi=4 a[mid]=5
lo=3 mid=3 hi=4 a[mid]=7
half-open: a=[1, 3, 5, 7, 9] target=7 -> index 3
lo=0 mid=2 hi=5 a[mid]=5
lo=3 mid=4 hi=5 a[mid]=9
lo=3 mid=3 hi=4 a[mid]=7
closed : a=[1, 3, 5, 7, 9] target=4 -> index -1
lo=0 mid=2 hi=4 a[mid]=5
lo=0 mid=0 hi=1 a[mid]=1
lo=1 mid=1 hi=1 a[mid]=3
lo=2 hi=1 -> interval empty
half-open: a=[1, 3, 5, 7, 9] target=4 -> index -1
lo=0 mid=2 hi=5 a[mid]=5
lo=0 mid=1 hi=2 a[mid]=3
lo=2 hi=2 -> interval empty
closed : a=[] target=5 -> index -1
lo=0 hi=-1 -> interval empty
half-open: a=[] target=5 -> index -1
lo=0 hi=0 -> interval empty
exhaustive cases checked: 3960 | max (steps - bit_length(n)): 0
n = 0 bound n.bit_length() = 0 | measured worst: 0
n = 1 bound n.bit_length() = 1 | measured worst: 1
n = 2 bound n.bit_length() = 2 | measured worst: 2
n = 3 bound n.bit_length() = 2 | measured worst: 2
n = 4 bound n.bit_length() = 3 | measured worst: 3
n = 5 bound n.bit_length() = 3 | measured worst: 3
n = 6 bound n.bit_length() = 3 | measured worst: 3
n = 7 bound n.bit_length() = 3 | measured worst: 3
n = 8 bound n.bit_length() = 4 | measured worst: 4
s=4: closed -> left 1, right 2 | half-open -> left 2, right 1 | s // 2 = 2
s=5: closed -> left 2, right 2 | half-open -> left 2, right 2 | s // 2 = 2
s=6: closed -> left 2, right 3 | half-open -> left 3, right 2 | s // 2 = 3
int32 max: 2147483647
true sum: 3500000000 | minus 2**32 = -794967296 (the wrap-around subtracts 2**32 from a sum above int32 max)
lo + hi wrapped: -794967296 -> (lo + hi) / 2 = -397483648
lo + (hi - lo) / 2 = 1750000000
mixed conventions on [1, 3, 5, 7] searching 3: -1
half-open on [1, 3, 5, 7] searching 3: 1
Reading the traces: the closed search for 7 stops at the second pass; the half-open search takes three passes on the same input (its second midpoint is index 4, not 3). The miss for 4 ends with lo=2, the insertion point between 3 and 5. The empty array never enters the loop: closed ends with lo=0 hi=-1, half-open with lo=0 hi=0.
Complexity
Time is O(log n) comparisons (at most n.bit_length() passes, shown above). Space is O(1): three integers and no recursion. The assertions in the shipped code cost O(n) per pass, so they are test instrumentation and are removed in production.
Edge cases and common mistakes
- Empty array: closed starts with
hi = -1, half-open withhi = 0; both skip the loop and return -1. - Duplicates: the search returns some index holding the target, not necessarily the first (on
[2, 2, 2, 2]the closed search below returns index 1). Finding the first needs a different invariant (everything left oflois strictly smaller, andhimoves on equality), covered by the lower-bound variant. - Mixing conventions: starting half-open (
hi = n) but updating withhi = mid - 1drops candidates. In the last two output lines, the mixed version misses 3 in[1, 3, 5, 7]and returns -1, while the half-open version finds it at index 1. - Using
while lo < hiwith a closed window skips the last single-element window: the table below returns -1 for[5]and for[1, 3]although the target is present. - Using
lo = midin a closed window can loop forever, since the window size need not shrink: the table below gives up after 50 passes on[1, 3]searching 3. - Writing
(lo + hi) // 2in a fixed-width language.
The two window mistakes and the duplicates case, run on a closed-window search with switches (it gives up after 50 passes instead of hanging):
def closed_search(a, target, strict_loop=False, lo_update="mid + 1", cap=50):
"""Closed-window search with switches for two mistakes; gives up after `cap` passes."""
lo, hi = 0, len(a) - 1
for _ in range(cap):
if (lo >= hi) if strict_loop else (lo > hi):
return -1
mid = lo + (hi - lo) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1 if lo_update == "mid + 1" else mid
else:
hi = mid - 1
return "no exit after 50 passes"
print("variant array target result")
for label, kwargs, a, t in (
("correct (lo <= hi, lo = mid+1)", {}, [5], 5),
("while lo < hi in a closed window", {"strict_loop": True}, [5], 5),
("while lo < hi in a closed window", {"strict_loop": True}, [1, 3], 3),
("lo = mid in a closed window", {"lo_update": "mid"}, [1, 3], 3),
("correct, duplicates", {}, [2, 2, 2, 2], 2),
):
print(f"{label:<33} {str(a):<13} {t:>6} {closed_search(a, t, **kwargs)}")
variant array target result
correct (lo <= hi, lo = mid+1) [5] 5 0
while lo < hi in a closed window [5] 5 -1
while lo < hi in a closed window [1, 3] 3 -1
lo = mid in a closed window [1, 3] 3 no exit after 50 passes
correct, duplicates [2, 2, 2, 2] 2 1
Running the code
Save the first program as binary_search_proof.py and the last one as binary_search_mistakes.py, and run them with Python 3.12 (standard library only). Save the Java snippet as MidpointOverflow.java and run it with JDK 21:
python3 binary_search_proof.py
python3 binary_search_mistakes.py
java MidpointOverflow.java
Implement a Python function that searches for a target in a rotated sorted array which may contain duplicates. Signature: def search_rotated_with_duplicates(nums: List[int], target: int) -> bool. Explain why duplicates may force worst-case O(n) behavior and demonstrate how your algorithm handles ambiguous comparisons.
Sample Answer
The idea in plain words
A rotated sorted array is a sorted array whose front part was moved to the back, such as [4, 5, 6, 7, 0, 1, 2]. The rotation point is the one place where the values drop (here 7 is followed by 0). Binary search still works on it because at any probe mid, at least one of the two halves lo..mid or mid..hi is a plain sorted run. You find the sorted half, check whether the target lies inside its value range, and keep that half or discard it.
Here is the picture for [4, 5, 6, 7, 0, 1, 2] with lo=0, mid=3, hi=6:
index: 0 1 2 3 | 4 5 6
value: 4 5 6 7 | 0 1 2
lo mid hi
The rotation point sits between index 3 and index 4, so it falls in the right half. The left half 4, 5, 6, 7 has no drop, so it is a plain sorted run: nums[lo] = 4 <= nums[mid] = 7. If the rotation point had fallen inside the left half, then nums[mid] would already be on the low side of the drop, below nums[lo]. So nums[lo] <= nums[mid] means "left half sorted", and nums[lo] > nums[mid] means "right half sorted".
With distinct values that test identifies the sorted half. With duplicates it can fail to: if nums[lo], nums[mid] and nums[hi] are all equal (a tie), you cannot tell where the rotation point is, so the comparison is ambiguous: it does not say which half is sorted. The only safe move is to give up a single element from each end, and when that keeps happening the search degrades to a scan: O(n) in the worst case.
The brute force is target in nums, O(n). The rotated binary search is O(log n) when ties are rare and O(n) in the worst case.
Why duplicates blur which half is sorted
[1, 0, 1, 1, 1] and [1, 1, 1, 0, 1] are two rotations of [0, 1, 1, 1, 1]. At the first probe (lo=0, mid=2, hi=4) both show 1, 1, 1: the three values the algorithm reads are identical, yet the 0 sits in the left half of one array and the right half of the other. Any rule that keeps only one half is wrong for one of them. Dropping nums[lo] and nums[hi] is safe, because both equal nums[mid], and nums[mid] is not the target (it was just compared), so neither dropped element could be the target.
When the three values are not all equal, the usual test is still correct. Suppose nums[lo] <= nums[mid] and yet the rotation point lay inside the left half. Then three things would hold at once:
nums[mid]sits after the drop, in the low run that continues tohi, sonums[mid] <= nums[hi].- Every value in that low run is at most every value before the drop, so
nums[hi] <= nums[lo]. - We assumed
nums[lo] <= nums[mid].
Chaining them gives nums[lo] <= nums[mid] <= nums[hi] <= nums[lo], which forces all three values to be equal. That is the tie the code handles first, so outside a tie the rotation point cannot be in the left half and the left half is sorted. In the [4, 5, 6, 7, 0, 1, 2] picture the chain would need 4 <= 7 <= 2 <= 4, which is false, as it should be.
The code
import itertools
import random
from typing import List
def _search(nums: List[int], target: int, trace=None):
"""Return (found, loop steps)."""
lo, hi = 0, len(nums) - 1
steps = 0
while lo <= hi:
steps += 1
mid = lo + (hi - lo) // 2
if trace is not None:
trace.append((lo, hi, mid, nums[lo], nums[mid], nums[hi]))
if nums[mid] == target:
return True, steps
if nums[lo] == nums[mid] == nums[hi]:
lo += 1 # ambiguous: cannot tell which half is sorted.
hi -= 1 # Neither end is the target, so drop both.
elif nums[lo] <= nums[mid]: # left half lo..mid is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half mid..hi is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return False, steps
def search_rotated_with_duplicates(nums: List[int], target: int) -> bool:
return _search(nums, target)[0]
def search_without_tie_rule(nums, target):
"""The textbook distinct-values version: it never handles nums[lo] == nums[mid] == nums[hi]."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return True
if nums[lo] <= nums[mid]:
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return False
def show(nums, target):
trace = []
found, steps = _search(nums, target, trace)
print(f"{nums} target={target} -> {found} in {steps} steps")
for lo, hi, mid, a, b, c in trace:
print(f" lo={lo} hi={hi} mid={mid} nums[lo], nums[mid], nums[hi] = {a}, {b}, {c}")
# No ties: the three probe values show which half is sorted.
show([4, 5, 6, 7, 0, 1, 2], 0)
print()
# Two different rotations of [0, 1, 1, 1, 1] look identical at the first probe.
show([1, 0, 1, 1, 1], 0)
show([1, 1, 1, 0, 1], 0)
print()
show([2, 5, 6, 0, 0, 1, 2], 0)
show([2, 5, 6, 0, 0, 1, 2], 3)
# Exhaustive check against 'target in nums' on every rotation of every non-decreasing list.
print("without the tie rule:", search_without_tie_rule([1, 0, 1, 1, 1], 0),
search_without_tie_rule([1, 1, 1, 0, 1], 0), "(both should be True)")
checked = 0
wrong_without_tie_rule = 0
for length in range(8):
for combo in itertools.combinations_with_replacement(range(4), length):
base = list(combo)
for k in range(max(length, 1)):
rotated = base[k:] + base[:k]
for t in range(-1, 5):
assert search_rotated_with_duplicates(rotated, t) == (t in rotated)
wrong_without_tie_rule += search_without_tie_rule(rotated, t) != (t in rotated)
checked += 1
print("\nexhaustive check passed:", checked, "cases;",
"the version without the tie rule is wrong on", wrong_without_tie_rule)
print("\nworst case: n equal values plus one 0 hidden somewhere, searching for 0")
print("n most steps over all rotations steps on an all-equal list without 0 distinct values, most steps")
for n in (16, 64, 256, 1024):
most = 0
for pos in range(n):
rotated = [1] * n
rotated[pos] = 0
most = max(most, _search(rotated, 0)[1])
absent = _search([1] * n, 0)[1]
distinct = 0
for k in range(n):
base = list(range(n))
rotated = base[k:] + base[:k]
for t in (0, n // 2, n - 1, n):
distinct = max(distinct, _search(rotated, t)[1])
print(f"{n:<6}{most:<32}{absent:<40}{distinct}")
print("\naverage steps over 2000 random cases (seed 5), n = 1024, random rotation, random target (often absent)")
rng = random.Random(5)
for label, top in (("values 0..3 ", 3), ("values 0..9999", 9999)):
total = 0
for _ in range(2000):
base = sorted(rng.randint(0, top) for _ in range(1024))
k = rng.randrange(1024)
rotated = base[k:] + base[:k]
total += _search(rotated, rng.randint(-1, top + 1))[1]
print(f" {label}: {total / 2000:.2f} steps on average")
The output below is the complete output of that program.
[4, 5, 6, 7, 0, 1, 2] target=0 -> True in 3 steps
lo=0 hi=6 mid=3 nums[lo], nums[mid], nums[hi] = 4, 7, 2
lo=4 hi=6 mid=5 nums[lo], nums[mid], nums[hi] = 0, 1, 2
lo=4 hi=4 mid=4 nums[lo], nums[mid], nums[hi] = 0, 0, 0
[1, 0, 1, 1, 1] target=0 -> True in 3 steps
lo=0 hi=4 mid=2 nums[lo], nums[mid], nums[hi] = 1, 1, 1
lo=1 hi=3 mid=2 nums[lo], nums[mid], nums[hi] = 0, 1, 1
lo=1 hi=1 mid=1 nums[lo], nums[mid], nums[hi] = 0, 0, 0
[1, 1, 1, 0, 1] target=0 -> True in 3 steps
lo=0 hi=4 mid=2 nums[lo], nums[mid], nums[hi] = 1, 1, 1
lo=1 hi=3 mid=2 nums[lo], nums[mid], nums[hi] = 1, 1, 0
lo=3 hi=3 mid=3 nums[lo], nums[mid], nums[hi] = 0, 0, 0
[2, 5, 6, 0, 0, 1, 2] target=0 -> True in 1 steps
lo=0 hi=6 mid=3 nums[lo], nums[mid], nums[hi] = 2, 0, 2
[2, 5, 6, 0, 0, 1, 2] target=3 -> False in 3 steps
lo=0 hi=6 mid=3 nums[lo], nums[mid], nums[hi] = 2, 0, 2
lo=0 hi=2 mid=1 nums[lo], nums[mid], nums[hi] = 2, 5, 6
lo=0 hi=0 mid=0 nums[lo], nums[mid], nums[hi] = 2, 2, 2
without the tie rule: False True (both should be True)
exhaustive check passed: 11094 cases; the version without the tie rule is wrong on 84
worst case: n equal values plus one 0 hidden somewhere, searching for 0
n most steps over all rotations steps on an all-equal list without 0 distinct values, most steps
16 9 8 5
64 33 32 7
256 129 128 9
1024 513 512 11
average steps over 2000 random cases (seed 5), n = 1024, random rotation, random target (often absent)
values 0..3 : 5.61 steps on average
values 0..9999: 9.92 steps on average
Reading the traces
[4, 5, 6, 7, 0, 1, 2], target 0: the first probe reads4, 7, 2. There is no tie and4 <= 7, so the left half is sorted; the target 0 is not in[4, 7), solo=4. The second probe reads0, 1, 2atmid=5: the left half0, 1is sorted but 0 is in[0, 1), sohi=4, and the third probe finds it.[1, 0, 1, 1, 1], target 0: the first probe reads1, 1, 1(ambiguous), solo=1, hi=3. The second probe reads0, 1, 1: the left half is sorted (0 <= 1) and the target lies in[0, 1), sohi=1. The third probe finds the 0. Three steps.[1, 1, 1, 0, 1], target 0: the same ambiguous first step, then1, 1, 0: the left half is judged sorted and the target is not in[1, 1), solo=3, and the third step finds it.[2, 5, 6, 0, 0, 1, 2], target 0 is found at the first probe; for target 3 the search ends after three steps withFalse. The first probe reads2, 0, 2:nums[mid]is smaller thannums[lo], so the right half is sorted and 3 is outside(0, 2], so it goes left.- Dropping the tie rule breaks it: the textbook version returns
Falsefor the first array andTruefor the second, and it is wrong on 84 of the 11,094 cases in the exhaustive check, while the shipped version matchestarget in numson all of them (every rotation of every non-decreasing list of length 0 to 7 over four values, targets -1 to 4).
Why the worst case is O(n), and the typical case is not
The table counts loop steps from the shipped function. An array of n equal values plus one hidden 0 (every one of the n possible positions tried) needs n/2 + 1 steps at worst (9, 33, 129, 513 for n = 16, 64, 256, 1024), and an all-equal list that has no 0 at all takes n/2 steps (8, 32, 128, 512). Each ambiguous step removes only two elements. Distinct values, by contrast, need only 5, 7, 9, 11 steps at worst (log2 n + 1).
This is not just a weakness of this code. Take n = 5. The arrays [0,1,1,1,1], [1,0,1,1,1], [1,1,0,1,1], [1,1,1,0,1] and [1,1,1,1,0] are all valid rotations of the same sorted list, and [1,1,1,1,1] is a valid input too. Picture an adversary: someone who chooses the array after seeing which positions you read, and answers every read with 1. If your method stops after reading only four of the five positions, the adversary still has two legal arrays to pick from, one with a 0 in the unread slot and one without, and the right answer for target 0 differs between them. So on the all-ones input any method that reads positions one at a time must read every position, which is n reads. No such method beats O(n) for this input family.
On random data with duplicates the average is far better: over 2,000 seeded cases with n = 1024, random rotations and random targets, arrays with values 0 to 3 averaged 5.61 steps and arrays with values 0 to 9999 averaged 9.92. The slow case needs long runs of equal values that sit exactly at lo, mid and hi. So the honest summary is: O(log n) typically, O(n) worst case, O(1) extra space.
Edge cases and common mistakes
- Empty list: the loop never runs, the result is
False. - One element:
lo == mid == hi, so the answer comes from the first comparison, or the tie branch empties the window. - All elements equal: only the tie branch runs, and the cost is n/2 steps.
- Not rotated at all (rotation by 0):
nums[lo] <= nums[mid]holds throughout and it behaves as an ordinary binary search. - Using
nums[lo] < nums[mid](strict) instead of<=: when the window has two elements (lo == mid) the left run is not recognised as sorted, and on[3, 1]with target 1 the search returnsFalse. - Shrinking only one end is also correct in the tie case, but dropping both ends halves the number of steps on an all-equal list.
- Skipping the tie rule: the examples above show exactly how it fails.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python rotated_search_demo.py
Save the program as rotated_search_demo.py. It uses only the standard library, and the output above is from Python 3.12.
Given a singly-linked list representing server log entries with timestamps, implement merge sort to sort the list in ascending timestamp order in Python. Signature: def sort_list(head: Optional[ListNode]) -> Optional[ListNode]. You must use O(1) extra linked-list nodes (no arrays) and explain how you find the midpoint.
Sample Answer
The idea
Merge sort fits a linked list well. A list cannot be indexed, but merge sort never needs indexing: it only needs to (1) cut the list in half, (2) sort each half, and (3) merge two sorted lists by relinking nodes. Merging relinks the existing next pointers, so no values are copied and no array is built.
The brute force is to copy the nodes into a Python list, call sorted, and rebuild the links. It is O(n log n) but uses O(n) extra memory and breaks the "no arrays" rule.
Finding the midpoint
Use two pointers that start at the head. slow moves one node per step and fast moves two. When fast reaches the end, slow has covered half the distance, so it sits at the end of the first half. Here fast starts at head.next (one step ahead). That choice matters: for a two-node list slow stays on the first node, giving a 1 + 1 split. If both started at head, a two-node list would split into 2 + 0 and the recursion would never shrink. The code cuts the list by setting slow.next = None; the second half starts at the old slow.next.
Midpoint by hand
The block below runs the same two-pointer walk on lists of 5, 4 and 2 nodes and prints where the pointers are after every step, then the two halves it produces. It also runs the merge step tail.next, b = b, b.next in its one-line form and as separate statements.
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def build(vals):
head = None
for v in reversed(vals):
head = Node(v, head)
return head
def walk(vals):
head = build(vals)
slow, fast = head, head.next
print(f"list {vals}: slow={slow.val} fast={fast.val if fast else None}")
while fast and fast.next:
slow = slow.next
fast = fast.next.next
print(f" step: slow={slow.val} fast={fast.val if fast else None}")
first, second = [], []
node = head
while True:
first.append(node.val)
if node is slow:
break
node = node.next
node = slow.next
while node:
second.append(node.val)
node = node.next
print(f" halves: {first} | {second}")
walk([10, 20, 30, 40, 50])
walk([10, 20, 30, 40])
walk([10, 20])
# The assignment used in merge, written both ways, on a fresh pair of nodes each time.
for form in ("one line", "separate"):
b = build([7, 8])
tail = Node(0)
if form == "one line":
tail.next, b = b, b.next
else:
taken = b
b = b.next
tail.next = taken
print(f"{form}: tail.next={tail.next.val} b={b.val}")
Complete output:
list [10, 20, 30, 40, 50]: slow=10 fast=20
step: slow=20 fast=40
step: slow=30 fast=None
halves: [10, 20, 30] | [40, 50]
list [10, 20, 30, 40]: slow=10 fast=20
step: slow=20 fast=40
halves: [10, 20] | [30, 40]
list [10, 20]: slow=10 fast=20
halves: [10] | [20]
one line: tail.next=7 b=8
separate: tail.next=7 b=8
Reading it: on 5 nodes fast runs off the end after two steps, with slow on the middle node 30, so the first half gets the extra node (3 + 2). On 4 nodes slow stops on 20 and the halves are 2 + 2. On 2 nodes slow never moves and the halves are 1 + 1, which is why fast has to start one step ahead. The last two lines show that the one-line assignment and the three separate statements do the same thing: Python evaluates the whole right side first (the old b and the old b.next), then assigns left to right, so tail.next receives the old b and b then moves to its next node.
Approach
- If the list has 0 or 1 nodes, it is already sorted.
- Split at the midpoint and sort each half recursively.
- Merge: keep a
tailpointer and repeatedly attach the smaller front node of the two lists. A dummy placeholder node avoids special-casing the first attachment. When one list runs out, attach the rest of the other in one step.
Stability (equal keys keep their original relative order) comes from one comparison: take the right node only when it is strictly smaller (b.ts < a.ts). On a tie the left node goes first, and the left half always holds the earlier entries.
Code
from typing import Optional
class ListNode:
def __init__(self, ts: int, tag: str = "", next: "Optional[ListNode]" = None):
self.ts = ts # timestamp, the sort key
self.tag = tag # log message id, used here to check stability
self.next = next
TRACE = False
def split_middle(head: ListNode) -> Optional[ListNode]:
"""Cut the list after its first half and return the head of the second half."""
slow, fast = head, head.next # fast starts one step ahead
while fast and fast.next:
slow = slow.next # slow moves 1 node
fast = fast.next.next # fast moves 2 nodes
second = slow.next
slow.next = None # detach the first half
return second
def merge(a: Optional[ListNode], b: Optional[ListNode]) -> Optional[ListNode]:
dummy = tail = ListNode(0) # the only extra node: a placeholder head
while a and b:
if b.ts < a.ts: # take b only when strictly smaller,
tail.next, b = b, b.next # so ties keep a (the earlier) first
else:
tail.next, a = a, a.next
tail = tail.next
tail.next = a or b # splice the leftover run in one step
return dummy.next
def sort_list(head: Optional[ListNode], depth: int = 0) -> Optional[ListNode]:
if head is None or head.next is None:
return head
second = split_middle(head)
if TRACE:
print(" " * depth + f"split {show(head)} | {show(second)}")
left = sort_list(head, depth + 1)
right = sort_list(second, depth + 1)
if TRACE:
before = f"{show(left)} + {show(right)}" # read before merge relinks nodes
merged = merge(left, right)
if TRACE:
print(" " * depth + f"merge {before} -> {show(merged)}")
return merged
def build(pairs):
head = tail = ListNode(0)
for ts, tag in pairs:
tail.next = ListNode(ts, tag)
tail = tail.next
return head.next
def to_pairs(head):
out = []
while head:
out.append((head.ts, head.tag))
head = head.next
return out
def show(head):
return "[" + " ".join(f"{ts}{tag}" for ts, tag in to_pairs(head)) + "]"
if __name__ == "__main__":
import random
logs = [(50, "a"), (20, "b"), (50, "c"), (10, "d"), (20, "e"), (30, "f"), (10, "g")]
TRACE = True
result = sort_list(build(logs))
TRACE = False
print("sorted:", show(result))
# Edge cases: empty, one node, all equal, already sorted, reversed
assert sort_list(None) is None
for case in ([(5, "x")], [(7, "a"), (7, "b"), (7, "c")],
[(1, "a"), (2, "b"), (3, "c")], [(3, "a"), (2, "b"), (1, "c")]):
assert to_pairs(sort_list(build(case))) == sorted(case, key=lambda p: p[0])
# 500 random lists (many ties) against Python's stable sorted(); the same
# node objects must come back, so nothing was copied.
random.seed(1)
for _ in range(500):
n = random.randint(0, 40)
pairs = [(random.randint(0, 6), f"t{i}") for i in range(n)]
head = build(pairs)
ids = set()
node = head
while node:
ids.add(id(node))
node = node.next
out = sort_list(head)
assert to_pairs(out) == sorted(pairs, key=lambda p: p[0])
node, got = out, set()
while node:
got.add(id(node))
node = node.next
assert got == ids
print("500 random lists: order and stability match sorted(), same node objects")
big = build([(random.randint(0, 10**6), "") for _ in range(100_000)])
ts = [p[0] for p in to_pairs(sort_list(big))]
print("100000 nodes sorted:", ts == sorted(ts))
Run in a python:3.12 container, it prints:
split [50a 20b 50c 10d] | [20e 30f 10g]
split [50a 20b] | [50c 10d]
split [50a] | [20b]
merge [50a] + [20b] -> [20b 50a]
split [50c] | [10d]
merge [50c] + [10d] -> [10d 50c]
merge [20b 50a] + [10d 50c] -> [10d 20b 50a 50c]
split [20e 30f] | [10g]
split [20e] | [30f]
merge [20e] + [30f] -> [20e 30f]
merge [20e 30f] + [10g] -> [10g 20e 30f]
merge [10d 20b 50a 50c] + [10g 20e 30f] -> [10d 10g 20b 20e 30f 50a 50c]
sorted: [10d 10g 20b 20e 30f 50a 50c]
500 random lists: order and stability match sorted(), same node objects
100000 nodes sorted: True
Reading the trace
Each log entry shows its timestamp followed by a letter tag (50a is timestamp 50, entry a). The tags exist to check stability: the two 50s end as 50a 50c (their input order), the two 20s as 20b 20e, and the two 10s as 10d 10g. The trace is indented by recursion depth. The first split cuts 7 nodes into 4 + 3, and the merge lines show each pair of sorted halves being combined from the bottom up.
Complexity
- Time: O(n log n). Halving gives about log2(n) levels. On each level, the splits walk each list once and the merges touch each node once, so every level costs O(n).
- Space: O(log n). The only extra memory is the recursion stack, at most ceil(log2(n)) + 1 frames (a frame is the record the interpreter keeps for each function call still in progress, and the stack of them is the recursion stack) (at most 18 frames for the 100,000-node run, far under Python's default limit of 1000), plus one dummy node alive at a time inside
merge. No array and no copy of any node.
Edge cases and common mistakes
- Empty list and single node return immediately (both tested).
- All-equal and already sorted or reversed input work unchanged (tested), and 500 random lists with many ties matched Python's stable
sortedby order and by node identity. - Mistake: starting
fastathead, which splits a two-node list into 2 + 0, so the recursion never shrinks. - Mistake: forgetting
slow.next = None. The first half is then still the whole list, sosort_listcalls itself on a list that never gets shorter and raisesRecursionErroron any list of two or more nodes. - Mistake: using
<=in the take-right test, which silently makes the sort unstable: equal keys come out reversed.
The next section runs all three.
The named mistakes, run
This program reads sort_list.py, makes each mistake as a one-line change to the source, and sorts a two-node list and a list of three equal keys.
import re
src = open("sort_list.py").read().split('if __name__')[0] # the listing without its demo
mutants = {
"the answer's code": src,
"fast starts at head": src.replace("slow, fast = head, head.next", "slow, fast = head, head"),
"no slow.next = None": re.sub(r"\n slow\.next = None[^\n]*", "", src),
"<= in the take-right test": src.replace("if b.ts < a.ts:", "if b.ts <= a.ts:"),
}
inputs = {
"two nodes": [(1, "a"), (2, "b")],
"three equal keys": [(7, "a"), (7, "b"), (7, "c")],
}
for name, code in mutants.items():
assert name == "the answer's code" or code != src
ns = {}
exec(code, ns)
for label, pairs in inputs.items():
try:
out = ns["to_pairs"](ns["sort_list"](ns["build"](pairs)))
result = " ".join(f"{ts}{tag}" for ts, tag in out)
except RecursionError:
result = "RecursionError"
print(f"{name:<27}{label:<18}{result}")
Run in a python:3.12 container, it prints:
the answer's code two nodes 1a 2b
the answer's code three equal keys 7a 7b 7c
fast starts at head two nodes RecursionError
fast starts at head three equal keys RecursionError
no slow.next = None two nodes RecursionError
no slow.next = None three equal keys RecursionError
<= in the take-right test two nodes 1a 2b
<= in the take-right test three equal keys 7c 7b 7a
Follow-ups
A bottom-up version merges runs of size 1, then 2, then 4, and so on, using loops instead of recursion. Each pass walks the list, detaches width nodes, detaches the next width nodes, merges the two and appends the result to the output; then width doubles. The only extra memory is a handful of pointers and the dummy node, so the space is O(1) (the pass count is about log2 n, and each pass is O(n)). Run on 7 values, it prints the list after each pass:
import random
class ListNode:
def __init__(self, ts, next=None):
self.ts, self.next = ts, next
def merge(a, b):
dummy = tail = ListNode(0)
while a and b:
if b.ts < a.ts:
tail.next, b = b, b.next
else:
tail.next, a = a, a.next
tail = tail.next
tail.next = a or b
return dummy.next
def cut(head, width):
"""Detach the first `width` nodes from head; return the rest."""
while head and width > 1:
head, width = head.next, width - 1
if not head:
return None
rest, head.next = head.next, None
return rest
def sort_list_bottom_up(head):
length, node = 0, head
while node:
length, node = length + 1, node.next
dummy = ListNode(0, head)
width = 1
while width < length:
tail, cur = dummy, dummy.next
while cur:
left = cur
right = cut(left, width)
cur = cut(right, width)
tail.next = merge(left, right)
while tail.next:
tail = tail.next
width *= 2
print(f"after pass with runs of {width // 2} merged into {width}:", end=" ")
show = dummy.next
vals = []
while show:
vals.append(show.ts)
show = show.next
print(vals)
return dummy.next
random.seed(3)
vals = [random.randint(0, 9) for _ in range(7)]
head = None
for v in reversed(vals):
head = ListNode(v, head)
print("input:", vals)
out, res = sort_list_bottom_up(head), []
while out:
res.append(out.ts)
out = out.next
print("result:", res, res == sorted(vals))
Complete output:
input: [3, 9, 8, 2, 5, 9, 7]
after pass with runs of 1 merged into 2: [3, 9, 2, 8, 5, 9, 7]
after pass with runs of 2 merged into 4: [2, 3, 8, 9, 5, 7, 9]
after pass with runs of 4 merged into 8: [2, 3, 5, 7, 8, 9, 9]
result: [2, 3, 5, 7, 8, 9, 9] True
A k-way merge combines k already sorted lists into one by repeatedly taking the smallest of the k front items (usually with a heap of the k fronts). For a stream of log entries arriving in order, you would sort chunks as they arrive and k-way merge the sorted chunks.
Running the code
python3 midpoint.py
python3 sort_list.py
python3 bottom_up.py
python3 mistakes.py
Save the listings as midpoint.py, sort_list.py, bottom_up.py and mistakes.py (Python 3.12, standard library only; mistakes.py reads sort_list.py from the same folder).
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
Count the number of inversions in an integer array (pairs i < j with a[i] > a[j]) in O(n log n). Explain the recurrence, why the count can need 64 bits, and how equal elements must be handled.
Sample Answer
The idea
An inversion is a pair of positions i < j whose values are out of order: a[i] > a[j]. The brute force checks all n(n-1)/2 pairs, which is O(n^2). The faster way reuses merge sort: while merging two sorted halves, you can count how many inversions go across the halves without looking at each pair.
Why it works: take a sorted left half and a sorted right half, where every left element originally sat before every right element. When you pick right[j] because it is smaller than left[i], it is also smaller than every left element after left[i] (the left half is sorted). So right[j] forms an inversion with all len(left) - i remaining left elements. One addition counts them all. Inversions inside a half are counted by the recursive calls, so the total is left_count + right_count + cross.
Code
import random
TRACE = False
WORK = {} # elements handled by the merges at each recursion depth
def sort_and_count(a, strict=True, depth=0):
"""Return (sorted copy of a, number of pairs i < j with a[i] > a[j]).
strict=True counts a pair only when the left value is strictly greater.
strict=False is the buggy variant that also counts equal pairs.
"""
if len(a) <= 1:
return a[:], 0
mid = len(a) // 2
left, left_count = sort_and_count(a[:mid], strict, depth + 1)
right, right_count = sort_and_count(a[mid:], strict, depth + 1)
merged, cross = [], 0
i = j = 0
while i < len(left) and j < len(right):
take_left = left[i] <= right[j] if strict else left[i] < right[j]
if take_left:
merged.append(left[i])
i += 1
else:
# right[j] is smaller than left[i] and than every later left item,
# because left is sorted: that is len(left) - i inversions at once.
merged.append(right[j])
cross += len(left) - i
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
WORK[depth] = WORK.get(depth, 0) + len(merged)
if TRACE:
print(" " * depth + f"merge {left} + {right} -> {merged} cross={cross}")
return merged, left_count + right_count + cross
def count_inversions(a):
return sort_and_count(a)[1]
def brute(a):
return sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] > a[j])
if __name__ == "__main__":
TRACE = True
print("tiny case [3, 1, 2], inversions:", count_inversions([3, 1, 2]))
print()
data = [5, 3, 2, 4, 1, 3]
print("inversions:", count_inversions(data))
TRACE = False
print("brute force:", brute(data))
# Work per level of the recursion on 8 items: the same for any input order
# (a reversed array is the input with the most inversions, not the most merge work)
WORK.clear()
count_inversions(list(range(8, 0, -1)))
print("elements merged per depth, n = 8:", dict(sorted(WORK.items())))
# Equal elements: [2, 2] has no inversion.
print("[2, 2] strict:", sort_and_count([2, 2])[1], " buggy tie rule:", sort_and_count([2, 2], strict=False)[1])
# Edge cases
for case in ([], [7], [4, 4, 4, 4], [1, 2, 3, 4], [4, 3, 2, 1], [-3, 5, -3, 0]):
assert count_inversions(case) == brute(case), case
print("edge cases ok: n=4 reversed ->", count_inversions([4, 3, 2, 1]), "= 4*3/2")
# 1000 random arrays with many duplicates and negatives
random.seed(7)
for _ in range(1000):
arr = [random.randint(-4, 4) for _ in range(random.randint(0, 25))]
assert count_inversions(arr) == brute(arr)
print("1000 random arrays match brute force")
# The tie rule is tripped by duplicates: the buggy variant disagrees somewhere.
random.seed(7)
bad = 0
for _ in range(1000):
arr = [random.randint(-4, 4) for _ in range(random.randint(0, 25))]
bad += sort_and_count(arr, strict=False)[1] != brute(arr)
print("buggy tie rule wrong on", bad, "of 1000 of the same arrays")
# Size of the count: a reversed array of n items has n(n-1)/2 inversions.
for n in (65_536, 65_537):
total = n * (n - 1) // 2
print(f"n={n}: {total} inversions, fits in signed 32 bits: {total <= 2**31 - 1}")
n = 100_000
print("n=100000 reversed:", count_inversions(list(range(n, 0, -1))), "=", n * (n - 1) // 2)
Run in a python:3.12 container, it prints:
merge [1] + [2] -> [1, 2] cross=0
merge [3] + [1, 2] -> [1, 2, 3] cross=2
tiny case [3, 1, 2], inversions: 2
merge [3] + [2] -> [2, 3] cross=1
merge [5] + [2, 3] -> [2, 3, 5] cross=2
merge [1] + [3] -> [1, 3] cross=0
merge [4] + [1, 3] -> [1, 3, 4] cross=2
merge [2, 3, 5] + [1, 3, 4] -> [1, 2, 3, 3, 4, 5] cross=5
inversions: 10
brute force: 10
elements merged per depth, n = 8: {0: 8, 1: 8, 2: 8}
[2, 2] strict: 0 buggy tie rule: 1
edge cases ok: n=4 reversed -> 6 = 4*3/2
1000 random arrays match brute force
buggy tie rule wrong on 820 of 1000 of the same arrays
n=65536: 2147450880 inversions, fits in signed 32 bits: True
n=65537: 2147516416 inversions, fits in signed 32 bits: False
n=100000 reversed: 4999950000 = 4999950000
Reading the trace
First the smallest case that shows the idea, [3, 1, 2]. It splits into [3] and [1, 2]. Merging [1] with [2] finds nothing out of order (cross=0). Merging [3] with [1, 2]: the 1 is smaller than 3, so it jumps ahead of the one remaining left item (cross += 1); the 2 is also smaller than 3 (cross += 1 again). The 3 pairs (3,1) and (3,2) are the only inversions, so the total is 2, as printed.
Now the 6-element trace.
The trace is indented by recursion depth, and cross is the number of inversions found in that merge. In the last (outermost) merge, [2, 3, 5] is merged with [1, 3, 4] and cross=5: the 1 jumps ahead of all three left items (3 inversions), the 3 on the right jumps ahead of only the 5 (1 inversion), and the 4 jumps ahead of the 5 (1 inversion). The right 3 is not counted against the left 3, because they are equal. The total is the left half's 3 (1 from [3] + [2], 2 from [5] + [2, 3]) plus the right half's 2 plus the 5 cross inversions, which is 10 and matches brute force.
The recurrence
Sorting and counting each half costs T(n/2) each, and the merge walks both halves once, which is Theta(n) work (a constant amount per element). So:
T(n) = 2 T(n/2) + Theta(n), with T(1) = Theta(1).
Theta(n) reads "grows in proportion to n": bounded above and below by constants times n. Unrolling means substituting the recurrence into itself level by level until the subproblems reach size 1.
Unrolling: level 0 does cn work; level 1 has 2 subproblems of size n/2, so 2 * c(n/2) = cn; level k has 2^k subproblems of size n/2^k, again cn. There are log2(n) + 1 levels, so T(n) = Theta(n log n). (The master theorem, a standard formula for recurrences of the form T(n) = a T(n/b) + f(n), gives the same result here with a = 2, b = 2, f(n) = Theta(n).) With n = 8 the run prints the elements merged at each depth: 8 at depth 0, 8 at depth 1 (two merges of 4) and 8 at depth 2 (four merges of 2). The levels each cost n and there are 3 = log2 8 merge levels, so about 8 * 3 = 24 element moves in total.
Space: O(n). The code builds new lists with slicing and merging, and the lists alive at once along one root-to-leaf path add up to O(n) items, plus O(log n) recursion depth.
Why the count can need 64 bits
The most inversions an array can have is n(n-1)/2, reached by a strictly decreasing array. That passes the signed 32-bit limit (2,147,483,647) once n reaches 65,537, as the run prints: n = 65,536 gives 2,147,450,880 (fits) and n = 65,537 gives 2,147,516,416 (does not). A 100,000-element reversed array has 4,999,950,000 inversions. In C, C++, Java or Go use a 64-bit integer (long long, long, int64) for the counter. Python integers have arbitrary precision, so there is no overflow here. A signed 64-bit counter holds up to 9.2e18 (2^63 - 1), which is enough for arrays of up to 2^32 = 4,294,967,296 elements (n(n-1)/2 is still below 2^63 - 1 there, and 2^32 + 1 elements would pass it).
Equal elements
The definition is strict: a[i] > a[j], so equal values are not inversions. In the merge, that means ties must go to the left side (left[i] <= right[j] takes left) and add nothing. The buggy variant takes right on a tie and wrongly adds len(left) - i. The run shows it: [2, 2] has 0 inversions but the buggy rule reports 1, and it is wrong on 820 of the 1000 random arrays used for the check. If the problem asked for non-strict pairs (a[i] >= a[j]), the tie rule would flip.
Edge cases and mistakes
- Empty and one-element arrays return 0 (tested), as do already sorted and all-equal arrays; a reversed array gives n(n-1)/2.
- Negatives work because only comparisons are used.
- Mistake: counting
cross += 1instead oflen(left) - i, which undercounts, because one right element is out of order with every remaining left element, not just one (the next section runs it). - Mistake: using a 32-bit counter in a fixed-width language (the run above prints where 32 bits stop being enough).
The counting mistake, run
This program reads inversions.py, replaces cross += len(left) - i with cross += 1, and compares both versions with the brute force on 1000 seeded random arrays.
import random
src = open("inversions.py").read().split('if __name__')[0] # the listing without its demo
mutant_src = src.replace("cross += len(left) - i", "cross += 1")
assert mutant_src != src
good, bad = {}, {}
exec(src, good)
exec(mutant_src, bad)
random.seed(11)
cases = [[random.randint(-4, 4) for _ in range(random.randint(0, 12))] for _ in range(1000)]
wrong = [a for a in cases if bad["count_inversions"](a) != good["brute"](a)]
assert all(good["count_inversions"](a) == good["brute"](a) for a in cases)
print("answer's code is right on all 1000 arrays")
print("cross += 1 is wrong on", len(wrong), "of 1000 arrays")
example = [4, 5, 1, 2]
print(f"e.g. {example}: brute force {good['brute'](example)}, cross += 1 gives {bad['count_inversions'](example)}")
Run in a python:3.12 container, it prints:
answer's code is right on all 1000 arrays
cross += 1 is wrong on 565 of 1000 arrays
e.g. [4, 5, 1, 2]: brute force 4, cross += 1 gives 2
Follow-ups
A Fenwick tree (binary indexed tree, an array-based structure that adds a value at a position and answers "how many values so far are at most x" in O(log n) each) over compressed values counts inversions in the same O(n log n) time with a different technique. Both approaches extend to "count pairs with a[i] > 2 * a[j]": in the merge-sort version, add a counting pass before each merge that sweeps the two sorted halves with two pointers and counts the right items whose double is below each left item; in the Fenwick version, query how many earlier values exceed 2 * a[j] before inserting a[j].
Running the code
python3 inversions.py
python3 mistakes.py
Save the listings as inversions.py and mistakes.py (Python 3.12, standard library only; mistakes.py reads inversions.py from the same folder).
Unlock Full Question Bank
Get access to all Sorting and Searching Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.