Keep a deficient interval of possible values and only the array segment containing occurrences from that interval. This is missing-value search by deficient value intervals:The precondition is that every original entry lies in . The loop invariant istogether with: every active entry lies in , and every original occurrence with a value in that interval is in the active segment. The whole array remains a permutation of its initial contents. Initially these assertions follow from the precondition and .
def missing(): Int = {
val n = a.length
var lo = 0L
var hi = n.toLong + 1L
var l = 0
var r = n
while (hi - lo > 1L) {
val p = lo + (hi - lo) / 2L
val k = partition(l, r, p.toInt)
if ((k - l).toLong < p - lo) {
hi = p
r = k
} else {
lo = p
l = k
}
}
lo.toInt
}After array partitioning, the low subinterval has occurrences and possible values. If it is deficient, retaining it preserves the loop invariant. Otherwise , while the original active count is strictly less than ; subtraction givesThus the high subinterval is deficient and retaining it also preserves the loop invariant. Discarded occurrences lie outside the new candidate interval. The loop variant is the positive integer , which strictly decreases because the midpoint is strictly internal. At exit the interval has one possible value and fewer than one occurrence, so
lo is absent from the entire original array. For the loop is skipped and zero is returned. The Long value bounds avoid overflowing ; every internal pivot is at most , so its checked mathematical range fits Int.For the time complexity, let be the interval width and its active occurrence count before iteration . The loop invariant gives , and binary search gives . Each two-way array partition costs . Until the width reaches one, the widths are bounded by , so the total scan work is bounded by a geometric series plus loop overhead: overall, hence for positive . Partitioning the full array again at every iteration would instead lose this bound. Auxiliary space complexity is .
Search only the suffix strictly after each candidate first index. This enforces distinct indices even when the target is twice an existing value. Compute the complement in
Long to prevent integer overflow: subtracting two Int values can require 33 signed bits.def twoSum(a: Array[Int], target: Int): (Int, Int) = {
def lowerBound(from: Int, wanted: Long): Int = {
var lo = from
var hi = a.length
while (lo < hi) {
val mid = lo + (hi - lo) / 2
if (a(mid).toLong < wanted) lo = mid + 1
else hi = mid
}
lo
}
var i = 0
while (i < a.length - 1) {
val wanted = target.toLong - a(i).toLong
val j = lowerBound(i + 1, wanted)
if (j < a.length && a(j).toLong == wanted) return (i, j)
i += 1
}
(0, 0)
}The outer loop invariant says that no solution has a smaller first index than
i, when a pair is written in increasing index order. A failed suffix binary search proves there is no partner for the current i, extending the excluded prefix by one. A successful return has and in exact integer arithmetic. At exhaustion, every possible ordered pair has been excluded, so the sentinel (0,0) means no solution. The inner loop invariant is the standard lower-bound partition, restricted to the suffix starting at i + 1.There are at most suffix searches, each taking running time, so the total is , customarily written for . Auxiliary space is . Empty and singleton arrays immediately return the sentinel. This is distinct-index two-sum by suffix lower bounds; a faster two-pointer technique is also possible on a sorted array, but the code here directly meets the requested search-based bound.
Patience sorting Created 2026-10-20 Updated 2026-11-05
Patience sorting processes values into piles by putting each next value on the leftmost pile whose top is at least that value, creating a new pile when none qualifies. The pile tops stay increasing, so binary search finds the destination. The number of piles equals the length of a longest increasing subsequence: each pile is nonincreasing in arrival order, while predecessor links across piles construct an increasing subsequence of that length. For
3,1,2,4, the tops evolve to 1,2,4, giving length three. Changing the comparison changes whether equality is allowed in the subsequence. Merging the completed piles can then produce a full sorted output.[ref]https://www.stat.berkeley.edu/users/aldous/Research/OP/patience.pdf. Aldous and Diaconis, patience sorting and increasing subsequences
Peter Ljunglöf Created 2026-10-14 Updated 2026-11-05
Peter Ljunglöf is a computer scientist and a coeditor, with Alex Gerdes and Jonas Almström Duregård, of Data Structures and Algorithms edited by Peter Ljunglöf and others. The book develops abstract data types alongside concrete representations and analysis of algorithms. Its comparison of linear search with binary search illustrates how assumptions about the stored data affect the available algorithm.[ref]
Homepage: www.chalmers.se/en/persons/peb/
Pile top in patience sorting 2026-11-05
A pile top in patience sorting is the currently exposed value on one pile. With the rule “place the next value on the leftmost pile whose top is at least ,” pile tops remain strictly increasing from left to right. Replacing the chosen top preserves that invariant: all earlier tops are smaller than , and later tops exceed the old chosen top and hence .
More strongly, top is the smallest possible last value of an increasing subsequence of length among the entries seen so far. A smaller last value leaves more options for extending that subsequence. For
3,1,2, the top arrays are [3], [1], [1,2]. binary search finds each replacement position in logarithmic time. The final top array gives the length but need not itself be a subsequence: 2,3,1 ends with tops [1,3], although1 appeared after3. Predecessor pointers are needed to reconstruct a witness. Running time Created 2026-10-20 Updated 2026-11-05
An algorithm's running time is its computational work on an input, measured either as elapsed time on a specified system or as an operation count under a cost model. Time complexity expresses how that count grows with input size. For binary search in a random-access sorted array, halving the candidate interval needs comparisons. The same index-based code on a linked representation need not have that cost. Worst-case, average-case and amortized bounds quantify different questions; a measured duration alone does not prove any asymptotic guarantee.
Search algorithm Created 2026-10-20 Updated 2026-11-05
A search algorithm looks for an object satisfying a specified condition within a collection or state space. Linear search inspects entries directly; binary search exploits sorted order; breadth-first search explores graph states by distance from a start. The specification should say whether to return one witness, every witness or proof of absence. A procedure that eventually finds every reachable witness may still fail to terminate when none exists in an infinite space. Representation and available structure determine which candidates can safely be ruled out without inspection.
Sorted array 2026-10-13
An array whose entries appear in nondecreasing order under a specified total order. The displayed inequalities allow repeated values.
For example, is a sorted array of integers. Inserting at index gives : with spare capacity, first shift one slot right. Appending would violate the sorted array property. Updating an entry also requires preserving the total order, or removing and reinserting it in a suitable position.
The useful combination is order plus direct indexed access: binary search eliminates a whole interval of candidates at each comparison, giving search time complexity under constant-cost comparisons and the array cost model. A sorted array is therefore attractive for many lookups between changes, while keeping it sorted can still require shifting work per insertion. A sorted linked list has the ordering information but does not supply the same constant-cost access to a middle index.
Sorting algorithm 2026-10-13
A sorting algorithm rearranges a finite sequence into nondecreasing order under a chosen total order on its keys. Its output must contain every input entry exactly once, including repetitions: producing ordered values is insufficient if entries are lost. Merge sort is one such algorithm; stable sorting adds a requirement about equal keys.
Sorting creates reusable structure: equal sort keys become adjacent, and a sorted array supports binary search. However, an algorithm correctness check must establish both sortedness and sorting permutation preservation. Replacing every entry by the smallest key can produce ordered keys while destroying the original data. Stable sorting imposes a third condition when equal sort keys occur: retain their arrival order.
For example, take complete sorting records , with the first component as the sort key and the letter as associated data. A correct output is . The sort keys are ordered, every complete sorting record remains, and the equal-key pairs keep before and before . The output satisfies sortedness and sorting permutation preservation, but fails stable sorting. The output has the right multiset of sort keys but loses and duplicates ; it fails sorting permutation preservation of complete sorting records.
To express stable sorting precisely, label every input occurrence by its original position, even when two complete sorting records have identical contents. Let be the output position of the occurrence originally at position . Besides sortedness and sorting permutation preservation, requireHere is the sort key function. Sorting by the pair under lexicographic order gives the same order as stable sorting by : the original position breaks ties without discarding associated data. For a two-field ordering, first apply stable sorting by the secondary sort key, then apply stable sorting by the primary sort key. The second pass retains the secondary order within each group of equal primary sort keys. For instance, first becomes by letter, then by number.
Strictly increasing subsequence 2026-10-14
A strictly increasing subsequence selects indices of a sequence with . Equal values cannot both occur in it. Its maximum possible length is , with ; in general for the weak longest increasing subsequence. Use strict comparisons in the dynamic programming recurrence relation and replace the first tail at least as large as the next value in the binary search algorithm.
Ternary comparison 2026-10-31
A single comparison returning one of three outcomes: less than, equal to, or greater than. A comparison model may count this as one operation even when a programming language expresses the outcomes using multiple Boolean tests. Binary search on ordered keys uses one such comparison per inspected position.
Time complexity Created 2026-09-24 Updated 2026-10-14
The time complexity of an algorithm bounds its number of computation steps as a function of its input length.
Specify both the size parameter and the operations counted. For binary search, take to be the number of array entries and count a three-way comparison of the target with one entry as one operation. Code using separate equality and less-than tests may perform two primitive tests per inspected entry; this changes a constant factor. The input size in bits is a different parameter when entries have variable-length representations.
Worst-case time complexity maximizes the count over permitted inputs of size . An absent target forces comparisons in linear search. For binary search, the worst-case count is for , attained by a target larger than every entry. Both have a best case of one comparison when the first inspected entry matches.
In Big O notation, the worst-case bounds are and respectively. Here means that fixed constants exist with for all . It is an upper bound, so a logarithmic count is also ; the sharper bound communicates its scaling better. The base of the logarithm changes only a constant factor.
For , linear search can require comparisons, whereas binary search needs at most , since . Doubling adds just one to the worst-case binary search count. These are operation counts, not measured machine runtimes. Translating them into logarithmic execution time assumes constant-cost indexed access, comparison and index arithmetic. Long entries can make comparison expensive; a linked list does not provide constant-cost access to an arbitrary middle index. Building or sorting the array is additional work: merge sort can provide order for many subsequent searches, but its cost belongs in the analysis too.
Two-sorted-array order statistic 2026-10-24
To obtain the -th smallest entry of two ascending sorted arrays of lengths , choose prefix lengths with . Search for the two boundary inequalities in the title, treating missing left boundaries as and missing right boundaries as . Then all selected entries precede all unselected entries, so their largest boundary value is the answer. If , decrease ; if , increase . These failures are monotone because one prefix grows as the other shrinks. Binary search thus takes comparisons when the shorter array supplies the searched prefix. Repeated values retain their multiplicities in the ranks.
Upper-bound search 2026-10-31
For a sorted array , find the unique boundary with . A binary search maintains , an excluded prefix , and an excluded suffix . At an interior midpoint , replace by when , and otherwise replace by . Sortedness preserves the loop invariant; the width is a decreasing loop variant. Termination at gives the boundary, including and . The time complexity is with constant-cost comparisons and indexed access. Unlike searching for , this formulation does not risk integer overflow at the largest representable key.