Arrays and Strings (DSA Core #1)
Arrays and strings are the default input in an OA, and most of the work is done by a handful of passes: two pointers, a window, prefix sums, binary search. The rest is knowing the exact cost of each operation so you can tell whether \(O(n^2)\) will finish.
What an array is, and what it costs
An array is one contiguous block. The address of element i is
base + i * sizeof(T), so reading a[i] is a multiply and an add. That is the
whole reason indexing is \(O(1)\) and every other structure is measured against it.
vector<int> a = {7, 3, 9, 1, 4};
a[2]; // O(1): base + 2*4
a.push_back(5); // amortized O(1): doubles capacity when full
vector keeps three things: a pointer, a size, and a capacity. When size ==
capacity, push_back allocates twice the space and copies. Total copying over
\(n\) appends is \(1 + 2 + 4 + \dots + n < 2n\), so the average cost per append is
constant even though the worst single append is \(O(n)\).
| Operation | Cost | Reason |
|---|---|---|
a[i] read/write |
\(O(1)\) | address arithmetic |
push_back / pop_back |
\(O(1)\) amortized | doubling |
insert / erase in the middle |
\(O(n)\) | shift the tail |
| scan for a value | \(O(n)\) | no order to exploit |
lower_bound on sorted data |
\(O(\log n)\) | binary search |
sort |
\(O(n \log n)\) | introsort |
Insert at the front and you move every element. That single fact is why queues are built on deques and why linked lists exist at all (Ch. 2).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.9cm, minimum height=0.75cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {7,3,9,1,4} {
\node[c, fill=blue!12] (n\i) at (\i*1.0,0) {\v};
\node[font=\scriptsize\ttfamily] at (\i*1.0,-0.62) {\i};
}
\node[font=\scriptsize\ttfamily, anchor=east] at (-0.65,-0.62) {index};
\draw[thick, blue!50] (0.35,0.55) -- (4.65,0.55);
\node[font=\scriptsize, text=blue!50!black, anchor=south] at (2.5,0.6) {one block, 5 x 4 bytes};
\end{tikzpicture}
Give a problem \(n = 10^5\) and a one-second limit. A single loop is fine, an \(O(n \log n)\) sort is fine, \(O(n^2)\) is \(10^{10}\) operations and will time out. Read the constraints before you read the problem carefully; they choose the algorithm for you.
push_back called amortized \(O(1)\) rather than \(O(1)\)?ASolution
One particular push_back can copy the whole buffer and cost \(O(n)\). The
average over \(n\) appends is constant because capacity doubles, so copies happen
at sizes 1, 2, 4, … and sum to less than \(2n\).
Strings are byte arrays with rules
std::string is a contiguous sequence of char. Indexing is \(O(1)\), substr
copies \(O(\text{len})\), and += is amortized \(O(1)\).
string s = "nvidia";
s[0]; // 'n'
s.substr(1, 3); // "vid" — (start, length), not (start, end)
s.size(); // 6, type size_t (unsigned)
Two rules that cause most string bugs:
s.size() - 1underflows whensis empty, becausesize()is unsigned.s.size() - 1becomes about \(1.8 \times 10^{19}\), not-1. Writeint n = (int)s.size();once and usen.tolower(s[i])is undefined for negativecharvalues (bytes ≥ 128). Cast:tolower((unsigned char)s[i]).
Character arithmetic is just integer arithmetic, which is why frequency counting
works: s[i] - 'a' maps 'a'..'z' to 0..25.
for (char ch : s)
if (ch >= 'a' && ch <= 'z') ++cnt[ch - 'a'];
Indexing by byte is not indexing by character. UTF-8 stores é in two bytes, so
s.size() counts bytes, and any problem about “characters” is really about
ASCII unless it says otherwise. In an OA, assume ASCII.
s.substr(2, 10) return when s has 5 characters?ASolution
Everything from index 2 to the end (“the rest”), because substr clamps the
length. It throws only when the start index is greater than size().
Two pointers
Two pointers replace a nested loop with two indices that only move forward. The total work is \(O(n)\) because each index visits each position at most once.
Opposite ends. Sorted input, looking for a pair that sums to a target:
bool hasPairSum(vector<int>& a, int target) { // a is sorted
int i = 0, j = (int)a.size() - 1;
while (i < j) {
int sum = a[i] + a[j];
if (sum == target) return true;
if (sum < target) ++i; // need a bigger number
else --j; // need a smaller one
}
return false;
}
The correctness argument is the invariant: if a[i] + a[j] < target, then a[i]
cannot pair with anything at or below j, so i is safe to discard. Each step
removes one candidate permanently. That is why the loop makes progress and why
the answer is not missed.
The same movement validates palindromes (s[i] != s[j]), reverses in place
(swap(s[i], s[j])), and merges two sorted arrays from the back.
Same direction. Slow writer, fast reader:
int removeDuplicates(vector<int>& a) { // sorted, in place
int w = 0;
for (int r = 0; r < (int)a.size(); ++r)
if (w == 0 || a[r] != a[w - 1]) a[w++] = a[r];
return w; // new length
}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum size=0.85cm, font=\small\bfseries},
cur/.style={c, fill=orange!40, very thick},
done/.style={c, fill=green!30},
p/.style={->, thick}]
\foreach \v [count=\i from 0] in {1,1,2,3,3} {
\ifnum\i<2 \node[done] at (\i*0.95,0) {\v};
\else \node[c] at (\i*0.95,0) {\v}; \fi
}
\draw[p] (0.95,-0.85) -- (0.95,-0.2) node[above, font=\scriptsize] {};
\node[font=\scriptsize, anchor=north] at (0.95,-0.85) {write (w=2)};
\draw[p] (3.8,-1.35) -- (3.8,-0.55);
\node[font=\scriptsize, anchor=north] at (3.8,-1.35) {read (r=4)};
\end{tikzpicture}
The invariant here: everything in a[0..w-1] is the deduplicated prefix, and
a[w] is the next slot to write. The reader looks at every element once.
a[i] after a[i] + a[j] < target not lose avalid pair?
ASolution
The array is sorted, so every element at or below j is \(\le a[j]\). If the
largest partner still gives a sum below the target, a[i] cannot pair with any
of them.
Sliding window
A window is two pointers with a maintained aggregate. When the window grows, you add one element; when it shrinks, you remove one. The cost per step must be \(O(1)\); if you recompute the sum each time, you have written the nested loop again.
Fixed size. Maximum sum of any k consecutive elements:
long long maxWindowSum(const vector<int>& a, int k) {
long long sum = 0, best = LLONG_MIN;
for (int i = 0; i < (int)a.size(); ++i) {
sum += a[i];
if (i >= k) sum -= a[i - k]; // drop the element leaving
if (i >= k - 1) best = max(best, sum);
}
return best;
}
Variable size. Longest substring with no repeated character:
int longestUnique(const string& s) {
vector<int> last(256, -1);
int start = 0, best = 0;
for (int i = 0; i < (int)s.size(); ++i) {
unsigned char c = s[i];
if (last[c] >= start) start = last[c] + 1; // jump past the repeat
last[c] = i;
best = max(best, i - start + 1);
}
return best;
}
The variable window works because the predicate “window is valid” is monotone:
once [start, i] is valid, every sub-window of it is valid. So start only moves
forward. If the property were not monotone (for example “contains exactly two
distinct values”), you would need a different structure, not a bigger window.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.75cm, minimum height=0.7cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {a,b,c,a,b,b} {
\node[c] (n\i) at (\i*0.8,0) {\v};
}
\draw[very thick, orange, rounded corners=3pt] (-0.45,-0.5) rectangle (2.85,0.5);
\draw[very thick, blue!55, rounded corners=3pt] (2.35,-0.9) rectangle (4.85,0.9);
\node[font=\scriptsize, text=orange!80!black, anchor=north] at (1.2,-0.95) {valid: "abc"};
\node[font=\scriptsize, text=blue!60!black, anchor=north] at (3.6,-1.35) {shrunk to "cab"};
\draw[->, thick, red!70!black] (3.2,1.15) -- (3.2,0.35);
\node[font=\scriptsize, anchor=south] at (3.2,1.15) {'a' repeats at index 3};
\end{tikzpicture}
A window over a count array (int cnt[26]) handles “longest substring with at
most k distinct characters”, anagrams, and minimum-window problems, as long as
you update the count on both ends and track how many distinct keys are non-zero.
start still only move forward?
ASolution
Removing characters from the left can only reduce the number of distinct values. If a window is valid, every suffix of it is valid, so the left edge never needs to move back.
Prefix and suffix sums
Range sums are the classic \(O(n)\) build, \(O(1)\) query trade. Define \(\text{pre}[0] = 0\) and \(\text{pre}[i] = a[0] + \dots + a[i-1]\). Then
\[ \sum_{i=l}^{r-1} a[i] = \text{pre}[r] - \text{pre}[l] \]
vector<long long> prefix(const vector<int>& a) {
vector<long long> pre(a.size() + 1, 0);
for (size_t i = 0; i < a.size(); ++i) pre[i + 1] = pre[i] + a[i];
return pre;
}
long long rangeSum(const vector<long long>& pre, int l, int r) { // [l, r)
return pre[r] - pre[l];
}
Use long long: \(10^5\) values of \(10^9\) sum to \(10^{14}\), which overflows a
32-bit int.
The suffix version runs right to left and is what you need when an element’s answer depends on everything after it — product of array except self, best suffix, maximum subarray from the right.
vector<long long> suffix(const vector<int>& a) {
vector<long long> suf(a.size() + 1, 0);
for (int i = (int)a.size() - 1; i >= 0; --i) suf[i] = suf[i + 1] + a[i];
return suf;
}
In 2D the same idea gives submatrix sums. With \(\text{pre}[i][j] = \sum_{r<i, c<j} a[r][c]\):
pre[i + 1][j + 1] = a[i][j] + pre[i][j + 1] + pre[i + 1][j] - pre[i][j];
and the sum of the rectangle [r1, r2) × [c1, c2) is the four-corner formula
pre[r2][c2] - pre[r1][c2] - pre[r2][c1] + pre[r1][c1];
\begin{tikzpicture}[font=\rmfamily, >=stealth,
g/.style={draw, thick, minimum size=0.72cm, font=\small}]
\foreach \i in {0,...,3} \foreach \j in {0,...,3}
\node[g, fill=blue!8] at (\j*0.75,-\i*0.75) {};
\draw[very thick, orange] (0.38,-0.38) rectangle (2.62,-2.62);
\node[font=\scriptsize, anchor=west, text=orange!80!black] at (2.9,-1.5) {add +};
\draw[very thick, orange] (1.13,-1.13) rectangle (3.38,-3.38);
\node[font=\scriptsize, anchor=west, text=orange!80!black] at (2.9,-2.2) {subtract once};
\node[font=\small, anchor=north] at (1.5,-3.15) {inclusion–exclusion: two strips overlap};
\end{tikzpicture}
Subarray sums equal to \(k\), divisibility by \(k\), and “count subarrays with
property” all reduce to: store how many times each prefix value has appeared in a
hash map, then look up pre[i] - k.
pre need \(n+1\) slots instead of \(n\)?ASolution
So the empty prefix has a home at index 0. Without it, rangeSum(0, r) has no
value to subtract and every query needs a special case.
Difference arrays
You have \(q\) range updates “add \(v\) to every element of [l, r]” and one final
read. Doing them directly is \(O(nq)\). A difference array does it in \(O(n + q)\) by
storing only the change at the boundaries.
\[ d[l] \mathrel{+}= v, \qquad d[r+1] \mathrel{-}= v, \qquad a[i] = a[i-1] + d[i] \]
vector<long long> diff(n + 1, 0); // one extra slot for r+1 == n
auto addRange = [&](int l, int r, long long v) { // inclusive [l, r]
diff[l] += v;
diff[r + 1] -= v;
};
// after all updates, rebuild
long long cur = 0;
for (int i = 0; i < n; ++i) {
cur += diff[i];
a[i] = cur;
}
Each update writes two cells. The final sweep integrates, because a prefix of
differences is exactly the accumulated value. The extra slot at n absorbs the
r + 1 write; without it you go out of bounds on an update that reaches the end.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.7cm, minimum height=0.65cm, font=\scriptsize}]
\foreach \v [count=\i from 0] in {0,0,0,0,0} \node[c] at (\i*0.75,0) {\v};
\node[font=\scriptsize, anchor=east] at (-0.5,0) {d};
\foreach \v [count=\i from 0] in {0,+3,0,0,-3} \node[c] at (\i*0.75,-1.1) {\v};
\node[font=\scriptsize, anchor=east] at (-0.5,-1.1) {after add(1,3,+3)};
\foreach \v [count=\i from 0] in {0,3,3,3,0} \node[c, fill=green!20] at (\i*0.75,-2.2) {\v};
\node[font=\scriptsize, anchor=east] at (-0.5,-2.2) {prefix};
\draw[->, thick] (1.0,-1.55) -- (1.0,-1.75);
\draw[->, thick] (3.0,-1.55) -- (3.0,-1.75);
\end{tikzpicture}
2D difference works the same way with four corner writes instead of two
(d[r1][c1] += v, d[r2+1][c1] -= v, d[r1][c2+1] -= v, d[r2+1][c2+1] += v)
followed by a 2D prefix sweep.
diff with exactly n slots?ASolution
addRange(l, n-1, v) writes diff[n], one past the end. Either allocate n+1
or guard the write.
Binary search: the invariant, not the vibes
The usual bug is not the idea, it is the loop. Three things must be fixed before
you write a line: what interval holds the answer, what mid means, and how the
interval shrinks.
Pick one template and keep it. This is “first index where the predicate is true”,
over the half-open interval [lo, hi):
template <class Pred>
int firstTrue(int lo, int hi, Pred pred) { // answer in [lo, hi], hi may be n
while (lo < hi) {
int mid = lo + (hi - lo) / 2; // no overflow, mid < hi
if (pred(mid)) hi = mid; // mid can be the answer
else lo = mid + 1; // mid definitely is not
}
return lo;
}
Why it terminates: mid < hi always, both branches shrink the interval, and
lo == hi ends the loop. Why it is correct: the invariant is “all indices below
lo are false, and the answer, if it exists, is in [lo, hi)”. Both branches
preserve it. Why no off-by-one: hi = mid keeps mid, lo = mid + 1 drops it,
so no index is skipped and none is retried forever.
(lo + hi) / 2 is a real overflow bug: with lo = 2e9 and hi = 2.1e9 the sum
wraps negative. lo + (hi - lo) / 2 cannot. In an OA on int indices it rarely
fires, but the habit costs nothing.
int lowerBound(const vector<int>& a, int target) { // first index >= target
int lo = 0, hi = (int)a.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo; // may be a.size()
}
Three templates, one rule each:
| Goal | Keep | Return |
|---|---|---|
first i with a[i] >= x |
hi = mid on >= |
lo |
first i with a[i] > x |
hi = mid on > |
lo |
exact match, [lo, hi] closed |
lo = mid + 1, hi = mid - 1 |
check a[lo] |
The closed-interval version is where people write while (lo <= hi) and then
forget hi = mid - 1, which loops forever when lo == hi. If you cannot state
the invariant out loud, do not use the closed version.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.72cm, minimum height=0.68cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {2,4,6,8,10,12,14} {
\ifnum\i<3 \node[c, fill=gray!18] at (\i*0.8,0) {\v};
\else \node[c, fill=green!25] at (\i*0.8,0) {\v}; \fi
}
\draw[very thick, blue!60] (1.75,-0.55) rectangle (5.35,0.55);
\node[font=\scriptsize, anchor=north] at (3.55,-0.75) {search range [3, 7)};
\node[font=\scriptsize, text=gray!60!black, anchor=north] at (0.8,-1.25) {all < 8: discarded};
\end{tikzpicture}
Rotated sorted arrays, peak finding, and “minimum in a rotated array” are the same
loop with a comparison against a[hi] or a[lo] instead of a pred call. The
trap is the case with duplicates: if (a[mid] == a[hi]) --hi; is a linear
degrade, not a bug, and you should say so in a comment.
while (lo <= hi) with hi = mid loop forever?ASolution
When lo == hi == mid, the hi = mid branch sets hi to itself, so the range
never shrinks. The half-open template avoids this by requiring lo < hi.
lowerBound returns n for a target larger than everything. Isthat an error?
ASolution
No. It means “no such index”. Check the return against a.size() before
indexing, or clamp if the problem wants something else.
Binary search on the answer
Sometimes the array is not the thing you search; the answer is. If you can
write a feasible(x) that is false up to some point and true after it, binary
search finds the smallest feasible x without ever enumerating candidates.
The recipe:
- Bound the answer:
lo = smallest possible,hi = largest possible. - Write
feasible(x)in \(O(n)\) (or \(O(n \log n)\)). - Binary search for the first feasible
x. - Prove monotonicity: if
xworks, every largerxworks.
Eating bananas with h hours and piles piles: speed s needs
\(\sum \lceil p_i / s \rceil\) hours, which decreases as s grows.
long long hoursNeeded(const vector<int>& piles, int speed) {
long long h = 0;
for (int p : piles) h += (p + speed - 1) / speed; // ceil division
return h;
}
int minEatingSpeed(const vector<int>& piles, int h) {
int lo = 1, hi = *max_element(piles.begin(), piles.end());
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (hoursNeeded(piles, mid) <= h) hi = mid;
else lo = mid + 1;
}
return lo;
}
(p + speed - 1) / speed is the integer ceiling; p / speed rounds down and
quietly undercounts hours by one per pile.
The same shape solves “split array into k parts minimizing the largest sum”
(predicate: can greedily cut into at most k parts each \(\le x\)), “ship packages
within d days”, and “minimum time to finish tasks”. The tell in the statement is
“minimize the maximum” or “maximum the minimum”.
The upper bound must be a value you know is feasible. For Koko that is
max(piles). For splitting, it is the total sum. Get the bound wrong and the
search returns a number that fails the check.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=1.0cm, minimum height=0.7cm, font=\small}]
\foreach \v/\i in {1/0, 2/1, 3/2, 4/3, 5/4, 6/5, 7/6} {
\ifnum\i<3 \node[c, fill=red!15] at (\i*1.05,0) {\v};
\else \node[c, fill=green!22] at (\i*1.05,0) {\v}; \fi
}
\node[font=\scriptsize, anchor=north] at (1.05,-0.55) {infeasible};
\node[font=\scriptsize, anchor=north] at (5.25,-0.55) {feasible};
\draw[very thick, orange] (3.55,-0.85) -- (3.55,0.85);
\node[font=\scriptsize, text=orange!80!black, anchor=south] at (3.55,0.85) {first feasible = answer};
\end{tikzpicture}
feasible(x) for binary search to work?ASolution
It must be monotone: false, false, …, true, true. If a larger x can fail
after a smaller one succeeded, there is no single boundary to find.
Sorting
In C++, std::sort is introsort: quicksort, heapsort when recursion gets deep,
insertion sort on small ranges. \(O(n \log n)\) worst case, not stable.
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Insertion | \(O(n)\) | \(O(n^2)\) | \(O(n^2)\) | \(O(1)\) | yes |
| Merge | \(O(n\log n)\) | \(O(n\log n)\) | \(O(n\log n)\) | \(O(n)\) | yes |
| Quicksort | \(O(n\log n)\) | \(O(n\log n)\) | \(O(n^2)\) | \(O(\log n)\) | no |
| Heapsort | \(O(n\log n)\) | \(O(n\log n)\) | \(O(n\log n)\) | \(O(1)\) | no |
| Counting | \(O(n+k)\) | \(O(n+k)\) | \(O(n+k)\) | \(O(k)\) | yes |
Counting sort is the one to remember for OA constraints on values: if the keys are
integers in [0, k) with k around \(10^6\), you can beat \(O(n \log n)\).
void countingSort(vector<int>& a, int k) { // values in [0, k)
vector<int> cnt(k, 0);
for (int x : a) ++cnt[x];
int w = 0;
for (int v = 0; v < k; ++v)
while (cnt[v]--) a[w++] = v;
}
Custom comparators must be a strict weak ordering: return false for equal
elements. Returning a <= b violates it and std::sort can read out of bounds.
sort(v.begin(), v.end(), [](const pair<int,int>& a, const pair<int,int>& b) {
if (a.first != b.first) return a.first < b.first;
return a.second > b.second; // tie-break: second descending
});
If the order of equal elements matters, use stable_sort. If you only need the
\(k\)-th element, nth_element is \(O(n)\) on average and does not sort the rest.
Sorting is also a preprocessing step: sorting by start time turns interval problems into a single sweep (Ch. 8), and sorting by value turns pair-search into two pointers.
return a <= b; in a comparator a real crash risk?ASolution
For equal elements it says both a < b and b < a, which is not a strict
weak ordering. The sort’s partitioning can then walk past the end of the range.
Frequency counting and character processing
When the alphabet is small, an array beats a hash map: no allocation, no hashing, cache-friendly, and it is one line to reset.
bool isAnagram(const string& a, const string& b) {
if (a.size() != b.size()) return false;
int cnt[26] = {0};
for (size_t i = 0; i < a.size(); ++i) {
++cnt[a[i] - 'a'];
--cnt[b[i] - 'a'];
}
for (int c : cnt) if (c != 0) return false;
return true;
}
Other standard moves with the same cnt[26]:
- first non-repeating character: build counts, then scan in order.
- can-form-palindrome: at most one odd count.
- run-length encoding: walk and count while
s[i] == s[i-1]. - grouping anagrams: sort each string or use the count vector as a map key.
string encode(const string& s) { // run-length encoding
string out;
for (int i = 0; i < (int)s.size(); ) {
int j = i;
while (j < (int)s.size() && s[j] == s[i]) ++j;
out += s[i];
out += to_string(j - i);
i = j;
}
return out;
}
For a bigger alphabet use unordered_map<char,int> or map<char,int> when you
need sorted keys. int cnt[128] covers ASCII and is the fastest option in an OA.
ASolution
Two strings are anagrams exactly when their sorted versions are identical, so sorting is a canonical form. Its cost is \(O(L \log L)\) per string.
String hashing and pattern matching
Rolling hash. Map a string to a number with a polynomial in a base \(B\):
\[ H(s) = \sum_{i=0}^{n-1} s[i] \cdot B^{\,n-1-i} \bmod M \]
With prefix hashes \(h[i]\) (first i characters) and powers of \(B\), any substring
hash is \(O(1)\):
\[ H(s[l..r]) = h[r+1] - h[l] \cdot B^{\,r-l+1} \bmod M \]
const long long MOD = 1'000'000'007, BASE = 131;
vector<long long> buildHash(const string& s, vector<long long>& pw) {
int n = (int)s.size();
vector<long long> h(n + 1, 0);
pw.assign(n + 1, 1);
for (int i = 0; i < n; ++i) {
pw[i + 1] = pw[i] * BASE % MOD;
h[i + 1] = (h[i] * BASE + s[i]) % MOD;
}
return h;
}
long long subHash(const vector<long long>& h, const vector<long long>& pw,
int l, int r) { // s[l..r], inclusive
long long v = (h[r + 1] - h[l] * pw[r - l + 1]) % MOD;
return v < 0 ? v + MOD : v;
}
A single 32-bit modulus admits collisions and, worse, is attackable. For an OA, two moduli (or one 61-bit prime) are enough; comparing the actual substring on a hash hit makes it exact at the cost of rare extra work.
KMP. The failure array f[i] stores the length of the longest proper prefix
of p[0..i] that is also a suffix. It tells you how far to fall back when a
mismatch happens, so the pattern pointer never restarts from zero.
vector<int> failure(const string& p) {
vector<int> f(p.size(), 0);
for (int i = 1, k = 0; i < (int)p.size(); ++i) {
while (k > 0 && p[i] != p[k]) k = f[k - 1];
if (p[i] == p[k]) ++k;
f[i] = k;
}
return f;
}
vector<int> searchAll(const string& s, const string& p) {
vector<int> hits, f = failure(p);
if (p.empty()) return hits;
for (int i = 0, k = 0; i < (int)s.size(); ++i) {
while (k > 0 && s[i] != p[k]) k = f[k - 1];
if (s[i] == p[k]) ++k;
if (k == (int)p.size()) {
hits.push_back(i - k + 1);
k = f[k - 1]; // allow overlapping matches
}
}
return hits;
}
Total work is \(O(n + m)\): i never decreases and k increases by at most one
per iteration, so the while fallbacks amortize. A naive find-in-a-loop is
\(O(nm)\), which is \(10^{10}\) for \(n = m = 10^5\) — the difference between passing
and not.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.68cm, minimum height=0.62cm, font=\scriptsize\bfseries}]
\foreach \v [count=\i from 0] in {a,b,a,b,a} \node[c] at (\i*0.72,0) {\v};
\node[font=\scriptsize, anchor=east] at (-0.4,0) {pattern};
\foreach \v [count=\i from 0] in {0,0,1,2,3} \node[c, fill=orange!25] at (\i*0.72,-0.95) {\v};
\node[font=\scriptsize, anchor=east] at (-0.4,-0.95) {f[i]};
\draw[->, thick, blue!60] (2.16,-0.4) -- (0.72,-0.4);
\node[font=\scriptsize, anchor=south, text=blue!60!black] at (1.44,-0.35) {mismatch: fall back to f[1]=0};
\end{tikzpicture}
Alternatives: Z-function (also \(O(n+m)\), easier to reason about for some),
std::string::find in practice (fast, but worst case \(O(nm)\)), and suffix
automata (overkill for an OA).
i moving forward after amismatch?
ASolution
The failure array says the pattern’s prefix of length f[k-1] already matches
the text ending at i. Only the pattern pointer jumps back; the text is never
re-read.
Bugs and boundaries that actually bite
size_tunderflow.for (int i = 0; i <= (int)v.size() - 1; ++i)with an empty vector is a huge number. Cast once:int n = v.size();.- Half-open versus closed.
[l, r)needsr - lelements,[l, r]needsr - l + 1. Pick one convention per problem and stay in it. - Empty input.
max_element,a[0], ands.back()are all undefined on empty containers. Handlen == 0before the loop, not inside it. - Overflow. Sums of \(10^5\) values up to \(10^9\) need
long long;midarithmetic needslo + (hi - lo) / 2; products in hashing need%after every multiply. - Comparator. Always
<and>, never<=; tie-break every field so the order is total. charsignedness.tolowerandisalphaneed(unsigned char)casts.- Modifying while iterating.
eraseinside a range-for invalidates the iterator. Use an index loop orremove_if. - Uninitialized memory.
vector<int> v(n);is zeroed,int a[n];is not. - Multiple test cases. Reset every global array and counter, and read the
count first (
int t; cin >> t;), not until EOF. - Recursion depth. \(10^5\) frames of a recursive DFS overflows the stack; use an explicit stack or raise the limit.
The last one is worth a habit: before submitting, trace the smallest input
(n = 0, n = 1), the largest, and one with duplicates or all-equal values. Most
wrong answers on an OA are not wrong ideas, they are these cases.
first?
ASolution
The returned index’s meaning: is it the first true or the last false, and is
the interval half-open or closed? Then check the predicate’s boundary value
(pred(lo) and pred(hi)), which is what decides the direction of the update.
Next: Linked Lists (DSA Core #2) — pointers, reversal, and the two-speed trick.