V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Lower and Upper Bound

Binary Search templates for duplicate ranges and insertion positions

Search for a boundary, not an exact match

lower_bound returns the first position whose value is at least the target. upper_bound returns the first position whose value is greater. Their half-open range [lo, hi) allows hi = n, so insertion after the final value needs no special case.

One comparison changes the meaning

Lower bound moves right while a[mid] < target. Upper bound also moves right on equality, using a[mid] <= target. The player runs both searches over the same duplicate-heavy array, then highlights the equal range [lower, upper).

1
2
2
2
3
5
5
7
8
9

lower_bound: start with half-open range [0, 10) (hi=n sentinel) for target 2.

1function lowerBound(a: number[], t: number): number {
2 let lo = 0, hi = a.length; // half-open range [lo, hi),hi=n sentinel
3 while (lo < hi) {
4 const mid = (lo + hi) >> 1; // probe
5 if (a[mid] < t) lo = mid + 1; // too small: answer is on the right
6 else hi = mid; // >= t: mid may be the answer
7 }
8 return lo; // meeting point = first value >= t
9}
10// upperBound: replace < with <=, so equality also moves right; first value > t
11// count = upperBound - lowerBound
target2
Phaselower_bound
[lo, hi)[0, 10) (hi=n sentinel)
mid—
1 / 14

Reliable library semantics

Each boundary takes O(log n) time and O(1) space. If the target is absent, lower and upper meet at the same insertion position and the count is zero. This is the behavior behind C++ lower_bound, Python bisect, and equivalent standard-library APIs.

Invariant: indices before lo are known to fail the boundary predicate, while indices at or after hi are known to satisfy it.

Review exact-match behavior first in Binary Search.