∑GateAndNet
PlannerSign Up
INTERMEDIATEFrequently Tested 4 min read 5 views

Searching & String Pattern Matching (Animated): Binary, Interpolation, Rabin-Karp & KMP

Overflow-safe Binary Search loop invariants, Rotated Array & Ternary Search, O(log log n) Interpolation Search, Rabin-Karp rolling modular hash & spurious hits, and animated KMP LPS matching.

1. Interactive Binary Search Interval-Halving Visualizer

Step through both Present (47, 12, 94) and Absent (50) keys to observe how low becomes the exact sorted insertion index (lower_bound) when low > high:

Interactive Step-by-Step Animation

Binary Search (Interval Halving)

Worst O(⌊log₂ n⌋ + 1)Space: O(1) iterativeInvariant: target ∈ [L..H]
Target Key: 47Probes Used: 0 / 4
[0]
7
L
[1]
12
[2]
19
[3]
24
[4]
31
[5]
38
[6]
47
[7]
56
[8]
63
[9]
72
[10]
85
[11]
94
H
Search for target = 47 in sorted array of 12 keys (max ⌊log₂(12)⌋ + 1 = 4 probes).
1 / 7

2. Binary Search Variants & Specialized Array Searches

  1. First Occurrence (lower_bound): Even when A[mid] == target, record ans = mid and set high = mid - 1 to keep searching left!
  2. Search in Rotated Sorted Array ([4, 5, 6, 7, 0, 1, 2]): At least one of the two halves A[low..mid] or A[mid..high] is guaranteed strictly sorted — check whether target lies inside the sorted half in O(1)\mathcal{O}(1) and halve in O(log⁡n)\mathcal{O}(\log n)!
  3. Interpolation Search: Probes position pos=low+⌊(target−A[low])(high−low)A[high]−A[low]⌋pos = low + \left\lfloor \frac{(target - A[low])(high - low)}{A[high] - A[low]} \right\rfloor. Achieves O(log⁡log⁡n)\mathcal{O}(\log \log n) on uniformly distributed keys, degrading to O(n)\mathcal{O}(n) on exponential distributions like [1,2,4,8,…,2n][1, 2, 4, 8, \dots, 2^n].

3. String Pattern Matching: Naive vs Rabin-Karp vs KMP (Animated)

AlgorithmPreprocessingMatching Time (Avg / Worst)Core Mechanism
Naive Sliding Window00O(nm)\mathcal{O}(nm) worst (e.g. T=an,P=am−1bT=a^n, P=a^{m-1}b)Resets j=0j=0, backs up ii
Rabin-KarpΘ(m)\Theta(m)Avg O(n+m)\mathcal{O}(n+m), Worst O(nm)\mathcal{O}(nm)Rolling Horner hash  mod q\bmod q; spurious hits on collision!
Knuth-Morris-Pratt (KMP)Θ(m)\Theta(m)Θ(n+m)\Theta(n + m) Worst-Case!LPS[] failure table; ii never decrements
Boyer-Moore$\Theta(m +\Sigma)$
Interactive Step-by-Step Animation

KMP String Matching (LPS Table)

Θ(n + m) GuaranteedSpace: O(m) LPS arrayText pointer i NEVER backs up!
Text Pointer i = 0 (Monotonic!) • Pattern Pointer j = 0Character Comparisons: 0
A
B
A
B
D
A
B
A
C
D
A
B
A
B
C
A
B
A
B
A
0
B
0
A
1
B
2
C
0
A
1
B
2
A
3
B
4
Precomputed LPS (Longest Proper Prefix also Suffix) table for "ABABCABAB": [0, 0, 1, 2, 0, 1, 2, 3, 4].
1 / 25
Key Formulas Summary
Binary vs Interpolation vs Jump vs Exponential Search Complexity
TBinary=O(log⁡n),TJump=O(n),TInterp, avg=O(log⁡log⁡n)  (worst O(n))T_{\text{Binary}} = \mathcal{O}(\log n), \quad T_{\text{Jump}} = \mathcal{O}(\sqrt{n}), \quad T_{\text{Interp, avg}} = \mathcal{O}(\log \log n) \;(\text{worst } \mathcal{O}(n))
Note: Always write mid = low + (high - low) / 2 to avoid signed 32-bit integer overflow in (low + high)!
KMP Prefix Function LPS[q] & Total Amortized Time
LPS⁡[k]=max⁡{ℓ<k+1:P[0..ℓ−1]=P[k−ℓ+1..k]},TKMP(n,m)=Θ(n+m)\operatorname{LPS}[k] = \max\big\{\ell < k+1 : P[0..\ell-1] = P[k-\ell+1..k]\big\}, \qquad T_{\text{KMP}}(n, m) = \Theta(n + m)
Note: j increments at most n times and decreases by >= 1 per LPS fallback => <= 2n total loop steps!
#Algorithms#Binary Search#Interpolation Search#KMP#Rabin-Karp#String Matching#GATE CS

Practice Questions on This Chapter (2)

Q1GATE CS 2022MCQMEDIUM
+2M • -0.67

In the Knuth-Morris-Pratt (KMP) string matching algorithm, what is the LPS[] (Longest Proper Prefix which is also a Suffix) array for the pattern P = "ABABACA"?

⚡ Click an option above to verify instantly
Q2GATE CS 2018NATEASY
+1M • 0 Neg

What is the maximum number of key comparisons made by standard iterative Binary Search (A[mid] == x, <, > counted as 1 three-way probe per iteration) when searching in a sorted array of 1,0001,000 elements?

Previous TopicNon-Comparison Linear Sorting (Counting, Radix, Bucket) & O(n) Order StatisticsNext Topic Graph Algorithms & Logics (Animated): BFS/DFS Edges, Topological Sort, SCCs & Dijkstra/Bellman-Ford