ArticleslgStudy

computer science

Two-way string-matching algorithm

Two-way string-matching algorithm is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Two-way string-matching algorithm rather than just read about it. In short: In computer science, the two-way string-matching algorithm is a string-searching algorithm, discovered by Maxime Crochemore and Dominique Perrin in 1991. It takes a pattern of size m, called a “needle”, preprocesses it in linear time O(m), producing information that can then be used to search for the needle in any “haystack” string, taking only linear time O(n) with n being the haystack's length.

Key takeaways

  • Two-way string-matching algorithm belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Two-way string-matching algorithm to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Two-way string-matching algorithm from memory before moving on to harder problems.

Reference excerpt

In computer science, the two-way string-matching algorithm is a string-searching algorithm, discovered by Maxime Crochemore and Dominique Perrin in 1991. It takes a pattern of size m, called a “needle”, preprocesses it in linear time O(m), producing information that can then be used to search for the needle in any “haystack” string, taking only linear time O(n) with n being the haystack's length. The two-way algorithm can be viewed as a combination of the forward-going Knuth–Morris–Pratt algorithm (KMP) and the backward-running Boyer–Moore string-search algorithm (BM). Like those two, the 2-way algorithm preprocesses the pattern to find partially repeating periods and computes “shifts” based on them, indicating what offset to “jump” to in the haystack when a given character is encountered. Unlike BM and KMP, it uses only O(log m) additional space to store information about those partial repeats: the search pattern is split into two parts (its critical factorization), represented only by the position of that split. Being a number less than m, it can be represented in ⌈log₂ m⌉ bits. This is sometimes treated as "close enough to O(1) in practice", as the needle's size is limited by the size of addressable memory; the overhead is a number that can be stored in a single register, and treating it as O(1) is like treating the size of a loop counter as O(1) rather than log of the number of iterations. The actual matching operation performs at most 2n − m comparisons. Breslauer later published two improved variants performing fewer comparisons, at the cost of storing additional data about the preprocessed needle:

The first one performs at most n + ⌊(n − m)/2⌋ comparisons, ⌈(n − m)/2⌉ fewer than the original. It must however store ⌈log φ {\displaystyle \varphi } m⌉ additional offsets in the needle, using O(log2 m) space. The second adapts it to only store a constant number of such offsets, denoted c, but must perform n + ⌊(1⁄2 + ε) * (n − m)⌋ comparisons, with ε = 1⁄2(Fc+2 − 1)−1 = O( φ {\displaystyle \varphi } −c) going to zero exponentially quickly as c increases. The algorithm is considered fairly efficient in practice, being cache-friendly and using several operations that can be implemented in well-optimized subroutines. It is used by the C standard libraries glibc, newlib, and musl, to implement the memmem and strstr family of substring functions. As with most advanced string-search algorithms, the naïve implementation may be more efficient on small-enough instances; this is especially so if the needle isn't searched in multiple haystacks, which would amortize the preprocessing cost.

Critical factorization Before we define critical factorization, we should define:

A factorization is a partition ⁠ ( u , v ) {\displaystyle (u,v)} ⁠ of a string x. For example, ("Wiki","pedia") is a factorization of "Wikipedia". A period of a string x is an integer p such that all characters p-distance apart are equal. More precisely, x[i] = x[i + p] holds for any integer 0 < i ≤ len(x) − p. This definition is allowed to be vacuously true, so that any word of length n has a period of n. To illustrate, the 8-letter word "educated" has period 6 in addition to the trivial periods of 8 and above. The minimum period of x is denoted as ⁠ p ( x ) {\displaystyle p(x)} ⁠. A repetition w in ⁠ ( u , v ) {\displaystyle (u,v)} ⁠ is a non-empty string such that: w is a suffix of u or u is a suffix of w; w is a prefix of v or v is a prefix of w; In other words, w occurs on both sides of the cut with a possible overflow on either side. Examples include "an" for ("ban","ana") and "voca" for ("a","vocado"). Each factorization trivially has at least one repetition: the string vu. A local period is the length of a repetition in ⁠ ( u , v ) {\displaystyle (u,v)} ⁠. The smallest local period in ⁠ ( u , v ) {\displaystyle (u,v)} ⁠ is denoted as ⁠ r ( u , v ) {\displaystyle r(u,v)} ⁠. Because the trivial repetition vu is guaranteed to exist and has the same length as x, we see that ⁠ 1 ≤ r ( u , v ) ≤ l e n ( x ) {\displaystyle 1\leq r(u,v)\leq \mathrm {len} (x)} ⁠. Finally, a critical factorization is a factorization ⁠ ( u , v ) {\displaystyle (u,v)} ⁠ of x such that ⁠ r ( u , v ) = p ( x ) {\displaystyle r(u,v)=p(x)} ⁠. The existence of a critical factorization is provably guaranteed. For a needle of length m in an ordered alphabet, it can be computed in 2m comparisons, by computing the lexicographically larger of two ordered maximal suffixes, defined for order ≤ and ≥.

The algorithm

The algorithm starts by computing a critical factorization of the needle n as the preprocessing step. This step produces the index (starting point) of the periodic right-half, and the period of this stretch. The suffix computation here follows the authors' formulation. It can alternatively be computed using the Duval's algorithm, which is simpler and still linear time but slower in practice.

Shorthand for inversion. function cmp(a, b) if a > b return 1 if a = b return 0 if a < b return -1

function maxsuf(n, rev) length ← len(n) cur_period ← 1 currently known period. period_test_idx ← 1 index for period testing, 0 < period_test_idx <= cur_period. maxsuf_test_idx ← 0 index for maxsuf testing. greater than maxs. maxsuf_idx ← -1 the proposed starting index of maxsuf

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Two-way string-matching algorithm

Start with the simplest possible case. Write down what Two-way string-matching algorithm claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Two-way string-matching algorithm before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Two-way string-matching algorithm ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Two-way string-matching algorithm

In research
Two-way string-matching algorithm appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Two-way string-matching algorithm in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Two-way string-matching algorithm is common in secondary-school and first-year university syllabi. It links to neighbouring topics String matching algorithms, so understanding it makes those chapters shorter.
In everyday life
Look for Two-way string-matching algorithm outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Two-way string-matching algorithm in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Two-way string-matching algorithm means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Two-way string-matching algorithm out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Two-way string-matching algorithm in simple terms?

In computer science, the two-way string-matching algorithm is a string-searching algorithm, discovered by Maxime Crochemore and Dominique Perrin in 1991. It takes a pattern of size m, called a “needle”, preprocesses it in linear time O(m), producing information that can then be used to search for t…

Why does Two-way string-matching algorithm matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Two-way string-matching algorithm?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Two-way string-matching algorithm.

Tags

  • String matching algorithms

Keep exploring