Stemming, Skip Pointers, Phrase Search and Tolerant Retrieval
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Inverted index and sorted postings lists — covered in Lecture 2 (The Inverted Index: From Words to Documents)
- Merge algorithm for postings intersection — covered in Lecture 2 (The Merge Algorithm: Answering AND With One Forward Pass)
- Skip pointers for faster postings traversal — covered in Lecture 2 (Query Optimization and Why Boolean Refuses to Retire)
- Tokenization and text preprocessing — covered in Lecture 3 (Tokenization Is Not Simple Splitting)
- Stop words and case normalization — covered in Lecture 3 (Stop Words, Normalization and Case Decisions)
- Porter stemming and morphological reductions — covered in Lecture 3 (Stemming, Lemmatization and Porter Rules)
4.1 Preprocessing Recap: Tokenization, Stop Words and Normalization
4.1.1 Why Simple Steps Are Hard
Why would splitting text into words need a full lecture? The answer is that each tiny choice changes what the index holds.
Splitting text looks like a chore anyone could do by eye. For a search engine it is a chain of judgment calls, and each call changes which documents match which query.
Tokenization (splitting running text into tokens) sounds simple. It is not. Punctuation, hyphens, numbers, and compounds all force decisions. A hyphen in state-of-the-art can mean one token or four. A number like 2026 can be a year, a count, or part of a code. Each decision changes the token stream that flows into the index.
Normalization (mapping variant surface forms to one canonical form) needs the same care. Upper case and lower case, accented and plain letters, and alternate number forms must map to one shape. Rules must fit the retrieval goal. A rule that helps one query set can hurt another, so there is no single safe default.
Think of preprocessing as a prep line in a kitchen. Raw text enters at one end. Tokenization chops it into pieces. Normalization washes the pieces into one shape. Stop-word handling, stemming, and lemmatization trim and sort them. Clean packs leave the line as index terms. The analogy breaks at one point: a kitchen serves one meal, while this line runs twice, once on documents at index time and once on queries at search time. Both runs must use the same chain, or matching breaks. A document indexed as State-of-art never meets a query split as state of the art.
Preprocessing chain: tokenize first, normalize second, then stop-word handling, then stemming or lemmatization. The same chain must run on documents and on queries. Any mismatch between the two chains loses matches.
Scope: these early steps decide the vocabulary. They cannot fix a bad split later. Assumption: text in the collection splits the same way as text in queries. Mixed languages, heavy compounds, or noisy input break that assumption and need extra rules.
Picture a line chart that tracks index size as each step is added. The horizontal axis lists the steps in order: raw tokens, after normalization, after stop-word removal, after stemming. The vertical axis shows term count. The curve drops steeply at stop-word removal and again at stemming. The takeaway is that early steps shrink the index a lot, so each one deserves care.
Two traps show up here. One is tuning rules on one query set and trusting them everywhere. The other is fixing documents but forgetting queries, so the two sides stop sharing terms.
Preprocessing turns raw text into shared index terms through one fixed chain. Tokenization and normalization lead, and the same chain must serve both documents and queries.
That chain leads straight to the hardest judgment call in it: which words to drop.
4.1.2 Stop Words and the To-Be-Or-Not-To-Be Problem
Stop words (very common words that mainly join other words) look easy to remove. Words such as to, the, be, on, and up seem to add little meaning. A first plan says to list every joining word and drop all of them.
The class tested that plan on one famous line: to be or not to be. Almost every word in the line is a joining word. Drop all of them and almost nothing is left to index.
Walk the line through the plan step by step. The tokens are to, be, or, not, to, be. Mark to, be, or, and to as stop words. Only not survives as a content word. A query for the full line then has one term to match on, and the phrase is gone. Bold answer: aggressive dropping empties the line. Sense-check: a title search for that line would fail, which proves the plan is too crude.
That failure sets up the real trade. Some systems keep a stop list near 300 terms. Others keep a very short list. The right size depends on the collection and on the queries. Dropping too much harms phrases and titles. Dropping too little leaves a large index with little gain. A public stop-word list was shown in class for review. The list builds a feel for which words are often dropped and which are kept when phrases matter.
Scope: stop-word removal helps plain term queries on large collections. Assumption: dropped words carry no useful signal. That assumption fails for phrase queries, titles, and lines like the one above, where the joining words are the content.
Stop-word removal is a trade between index size and phrase truth. Short lists protect phrases, long lists shrink the index, and the collection plus the queries decide the point between them.
4.1.3 Normalization Needs Rules
Normalization maps forms such as lower case and upper case, accented and plain letters, and number forms to one shape. Each mapping needs a stated rule. Case folding maps Apple to apple. Accent stripping maps resume with accents to a plain form. Number rules decide whether 1,000 equals 1000.
Without rules, two copies of the same word miss each other at match time. With bad rules, two different words collapse into one. A rule that folds all case helps Apple the fruit meet apple the query, but it also merges the company name with the fruit. State each rule, then test what it merges and what it splits.
Every normalization mapping needs a written rule and a check on what it merges. Rule-free folding loses matches, and careless folding creates false ones.
4.1.4 Student Questions and Answers
Q: What topic did we start with in preprocessing?
A: The chain started with tokenization, then normalization, then stop words, then stemming and lemmatization. Porter's algorithm was the last item left open from the prior session, so it comes next.
That open item is where the lecture turns next: conditioned stemming rules.
4.2 Porter Stemming Rules
4.2.1 What Stemming Does
Why cut words down at all? Because am, are, and is all point at the same idea, and an index that stores all three wastes space and splits matches.
A search engine does not need every surface form. It needs one shared form per idea, so that a query with one form still meets documents written with another.
Stemming (cutting inflected words to a shorter stem) trades meaning for compact matching. A stemmer can map am, are, and is to be. Then the sentence the boys cars are different colors becomes the boy car be different color. Much of the sense stays. The forms are shorter and fewer, so the index shrinks and recall rises.
The word stem means the crude cut form. It may not be a real word. The word lemma means the dictionary base form. So comput can be a stem without being a word, while compute is the lemma a dictionary would list. That contrast matters for the next sections, where lemmatization keeps real words and stemming does not.
Stemming maps many surface forms to one crude stem. The index gets smaller and matches get broader, at the cost of exact sense.
4.2.2 Porter Rules in Plain Words
Porter's algorithm (a rule-based stemmer for English) applies suffix rules with conditions. It runs in five phases of reductions, applied in order. Within each phase, the rule that matches the longest suffix wins. Many later rules also check a length guard before they cut.
The first-phase plural rules from class behave like this. Words ending in SSES map to SS, so caresses goes to caress. Words ending in IES map to I, so ponies goes to poni in the reference form (heard in class as pony). Words ending in SS stay as SS, so caress stays caress. A lone trailing S drops, so cats goes to cat.
Pairs such as relational going to relate and conditional going to condition show the middle phases. The ending ational reduces to ate, and the ending tional reduces to tion. A word such as cement is left alone because the stem would be too short.
Porter measure guard: with for the stem measure and for the stem string, a conditioned rule fires only when the guard holds:
Here is a count of vowel-consonant groups in the stem (a rough syllable count), and is a string. The guard checks that the stem is long enough for the matched part to count as a suffix rather than as part of the stem itself.
The reconciled rule behind the garbled class wording is the EMENT rule. In full form, with the ending EMENT removed when the guard holds:
Here is the stem measure and EMENT is the suffix letters. Walk it on two words. For replacement, the stem before the ending is replac, whose measure clears the guard, so EMENT drops and replacement maps to replac. For cement, the stem before the ending is c, whose measure is too small, so the rule is blocked and cement stays cement. Bold answer: replacement shortens, cement is untouched. Sense-check: a one-letter stem cannot be a real base, so blocking the cut is the safe move.
Work the class examples end to end. Caresses ends in SSES, so the plural rule maps it to caress. Ponies ends in IES, so the reference rule maps it to poni (heard in class as pony). Relational ends in ational, so it maps to relate. Conditional ends in tional, so it maps to condition. Cement ends in EMENT, but its stem c is too short for the guard, so it stays cement. Bold answer: four words shorten, cement is blocked. Sense-check: every fired rule had a long enough stem, and the one short stem was refused.
Search engines use Porter-style stems to conflate plurals and verb forms before indexing. Plurals, verb endings, and common derivations collapse into shared stems, which keeps the vocabulary small.
Exam note: when a Porter rule is quoted, state the condition first and the replacement second. Marks go to the condition, not just the shortened word. Name the guard, name the ending, then give the result.
4.2.3 Why the Rules Are English-Specific
The rules fit English spelling habits: plurals in S, past forms in ED, progressive forms in ING, and Latin-style endings such as ational and tional. An old working guess was that most web browsing used English, near 90 percent English and 10 percent other languages at that time. That share has shifted since. Still, the rules were built round English plurals and verb endings, so they do not transfer as-is to other languages. Each language needs its own suffix tables and its own guards.
Scope: Porter fits English text with standard spelling. Assumption: suffix letters mark grammar rather than sense. That assumption fails for short words, names, and other languages, where the same letters belong to the stem.
Porter is an English tool. New languages need new rule tables, not the same endings with new data.
4.2.4 Student Questions and Answers
Q: If the rule turns ational into ate, does national become net? That makes no sense.
A: The doubt is fair, and it shows the limit of plain cutting. Porter does not chop blindly. It checks conditions such as the measure guard and controls errors before it cuts. Still, no single rule set fits all words, and odd stems slip through. New papers keep proposing other stemming methods. The class uses Porter to show the idea of conditioned rules, not as a final fix for every word.
On crudeness, a second question followed.
Q: Is plain stemming even cruder than Porter?
A: Yes. Plain stemming can cut off endings such as O and AL without checks. Porter adds conditions, so it cuts with more care. Both can still produce odd stems, but Porter blocks the worst cuts on short words.
The same trade between crude cuts and careful cuts drives the next set of stemmers.
4.3 Other Stemmers: Lovins, Paice-Husk and Snowball
4.3.1 Lovins Stemmer
What if speed matters more than sense? That question leads to the oldest stemmer in this set.
Some engines index huge collections on weak hardware. For them, one fast pass over each word beats a careful multi-phase analysis, even if some stems look odd.
The Lovins stemmer (a single-pass stemmer with about 250 rules) removes the longest matching suffix in one pass. In plain words, with for the input word and for the longest known suffix of :
Here is a string and is a string. One pass, longest match, done. The method is fast. It is less flexible and at times less accurate because many strict rules can overfit to narrow cases. A rule written for one ending keeps firing on words where that ending belongs to the stem.
Lovins trades care for speed: one pass with the longest matching suffix. Fast to run, but strict rules over-cut some words.
4.3.2 Paice-Husk Stemmer
The Paice-Husk stemmer (an aggressive iterative stemmer) applies rules again and again over several passes. First-pass stems go back through the rules for a second and third pass. Each pass strips more letters, so the stems come out shorter than with one-pass methods. For some domains the scores are still strong, which can feel surprising given how short the forms look. Short forms conflate more variants, and on narrow vocabularies that extra conflation helps recall more than it hurts precision.
Think of sanding wood. Lovins makes one pass with coarse paper. Paice-Husk sands, checks, and sands again until the surface is smooth. The piece ends up smaller, and sometimes too small, but the finish is even. The analogy breaks where words are concerned: wood has no meaning to lose, while a stem can sand away sense.
Paice-Husk re-applies its rules until nothing more strips off. Stems end shortest of all, which suits narrow domains and hurts general text.
4.3.3 Snowball Stemmer
The Snowball stemmer (a cleaner and more structured revision of Porter ideas) supports many languages, not just English. It keeps the conditioned-rule style but with tidier rule tables and language modules. Snowball is also the name of the rule-writing language behind it, so adding a language means writing a new stemmer in that language rather than patching English tables. Teams that index mixed-language collections pick Snowball because one framework covers many languages with the same conditioned-rule habit.
Snowball keeps Porter's conditioned style but packages it per language. It is the pick when the collection spans languages.
4.3.4 Worked Comparison on One Sample Passage
The same sample text was run through three stemmers. The passage reads: Such an analysis can reveal features that are not easily visible from the variations in the individual genes and can lead to a picture of expression that is more biologically transparent and accessible to interpretation.
With Lovins, endings were cut hard. Analysis became analys. Features became featur. Easily became eas. Visible became vis. Variations became vari. Expression became expres. Individual became individu. Genes became gen. The cuts changed both shape and sense, and forms like th for the show how far one pass can go. The result felt hard to trust for meaning, though it could suit a light and fast engine where speed matters more than exact sense.
Porter answers the same passage with more care.
With Porter, more of each word stayed. Analysis became analysi. Reveal stayed reveal. Easily became easili. Visible became visibl. Variation became variat. Genes stayed close to gene. Expression became express. The balance was better than Lovins. One odd point stayed: cutting a single last letter can feel pointless, yet that is how the rule table behaves on that word. Bold answer: Porter keeps readable stems where Lovins chops them. Sense-check: reveal surviving whole while vis shortens shows conditions firing per word, not blind cuts.
With Paice-Husk, words were cut shortest of all: analys, rev, feat, vary, pict, transp. Forms looked heavily chopped, worse than Lovins on this passage. The lesson is practical. No stemmer wins on every text. The problem at hand decides which stemmer to pick. A Porter-style stem also shows the wider risk: stems such as oper group operate, operating, operation, operative, and operational into one form, so a query for operating system starts matching documents about operational research.
Real-world: teams building retrieval or NLP pipelines test several stemmers on their own data before they lock one in. They measure speed and match quality on their own queries, not on a demo passage.
Scope: demo passages show habits, not verdicts. Assumption: the sample text stands for the full collection. That assumption fails when the collection uses narrow jargon, where aggressive cuts can still win.
Lovins cuts once and hard, Porter conditions each cut, Paice-Husk keeps cutting. The passage shows the habit of each, and the collection picks the winner.
4.3.5 Student Questions and Answers
Q: Which stemmer should we pick from this demo?
A: Pick by task. Use the demo as a starting feel, then test on your own collection. Check both speed and match quality. A stemmer that looks bad here can still win in a narrow domain where its conflations match the vocabulary.
Where stemming cuts too crudely for sense-heavy tasks, the next tool keeps real words instead.
4.4 Lemmatization: Rule-Based, Dictionary-Based, Hybrid and POS Tagging
4.4.1 What Lemmatization Does
What if the crude stem is the problem? Then stop cutting and start looking words up.
Some tasks cannot afford a wrong conflation. Telling river bank from money bank wrongly flips the whole meaning, so these tasks pay extra compute to keep real words.
Lemmatization (mapping each word to its base dictionary form) keeps real words. The base form is called the lemma. Where stemming cuts computing and computer to one crude comput shape, lemmatization tries to keep the true base of each. That care costs more work: dictionary lookups, ending rules, and often a grammar analysis of the sentence.
A tiny contrast helps. Easy maps to easy as its own base. A chopped stem such as gen has no clear base. It could point to gene or to generation. After heavy stemming, asking for the lemma of a broken stem often has no good answer. The stem destroyed the signal the lemmatizer needs.
Stemming cuts to a crude shared shape that may not be a word. Lemmatization maps to the true dictionary base word. The first is cheap conflation, the second is careful normalization.
Think of stemming as nicknames in a big family: everyone called Jon, Jonny, and Jonathan answers to Jon. Fast, but two different Jonathans merge. Lemmatization is checking ID cards: each person keeps their legal name. Slower, but no wrong merges. The analogy breaks where cost is concerned: checking IDs scales badly to millions of documents.
Lemmatization keeps real base words at a higher compute cost. Once a stem is chopped to gen, even a good lemmatizer cannot tell gene from generation.
4.4.2 Three Families
Rule-based lemmatization applies ending rules, much like stemming but aimed at real base forms. Dictionary-based lemmatization looks up the base form in a word list, so saw as a noun stays saw while saw as a verb maps to see. Hybrid lemmatization joins rules, dictionary lookup, and part-of-speech tagging (labeling each word as noun, verb, adjective, and so on). The tag helps pick the right base when one shape has two senses. Rules propose, the dictionary checks, and the tag breaks ties.
Rules handle the common shapes, the dictionary handles the odd forms, and grammar tags break ties between senses.
4.4.3 Part-of-Speech Tagging With the Bank Example
Take the word bank. In a swimming text, bank means river bank. In a finance text, bank means the place to keep money. The letters match. The sense does not.
Tag the sentence first: in swimming tales bank is tagged as a noun near water, swim, and river. In finance news bank is tagged near money, loan, and account. Part-of-speech tagging plus nearby words helps the code tell river bank from money bank. That sense pick then guides the lemma choice and later matching. Bold answer: the same letters get different lemmas because the tags and neighbors differ. Sense-check: a query for river bank should not return loan documents, which is exactly what the tag prevents.
Grammar tags plus nearby words pick the sense first. The lemma follows the sense, not the letters.
4.4.4 Named Lemmatizers
Real-world starting points from class: the WordNet lemmatizer from the Python NLTK library is a common baseline. The spaCy lemmatizer from the Python spaCy library is widely used in pipelines. The Stanford lemmatizer and TextBlob are also used. The advice from class was to explore and test rather than pick one because a random web post suggests it. Match the tool to the data: check language coverage, speed on the collection size, and accuracy on the query types before locking one in.
Scope: off-the-shelf lemmatizers fit standard edited text. Assumption: the dictionary covers the vocabulary. Heavy jargon, new product names, and mixed languages break that assumption and need custom entries.
Start with WordNet or spaCy, compare with Stanford or TextBlob, and keep the one that scores best on the real queries.
4.4.5 Student Questions and Answers
Q: What does part-of-speech tagging add beyond rules and a dictionary?
A: It adds context. Rules plus a dictionary can still pick the wrong base when one word has two senses. Tags such as noun or verb, read with nearby words, point to the right sense. Bank as river edge and bank as money house need that extra signal, and the tag supplies it.
With both tools on the table, the next question is when to pay for each.
4.5 Stemming Versus Lemmatization: When to Use Which
4.5.1 Speed Against Correctness
The whole choice fits in one line: pay with compute or pay with mistakes.
A web engine shows ten links and lets the reader pick the best one. A chatbot gets one answer and must get the sense right. Those two tasks need different tools.
Stemming is light and fast. Lemmatization is heavy and careful. When exact sense matters less and many options can be shown, stemming is often enough. Web search can show ten links and let the reader pick. Then index-time speed and small indexes matter most. When sense and context matter a lot, lemmatization fits better. Sentiment analysis, chatbots, and query understanding need the river-bank against money-bank split to be right, because one wrong sense flips the answer.
A good rule of thumb from class: stemming gives cheap conflation for indexing, while lemmatization gives sound normalization for understanding. In plain words, use stemming for fast index forms and lemmatization for careful query sense when both are in play.
| Dimension | Stemming | Lemmatization |
|---|---|---|
| Output | Crude stem, maybe not a word | True dictionary base word |
| Cost | Light and fast | Heavy, needs dictionary plus tags |
| Recall vs precision | Lifts recall, risks precision | Protects precision on sense-heavy queries |
| Pick it when | Many results shown, speed matters | One answer needed, sense matters |
Pick stemming for broad indexing and lemmatization for careful understanding.
Match the tool to the cost of a mistake. Cheap mistakes take stemming, costly ones take lemmatization.
4.5.2 Hybrid Pipelines and Order Effects
Some NLP pipelines list both steps, either lemmatization then stemming or stemming then lemmatization. Blindly stacking both can harm scores. A stem step can break the forms that the lemma step needs, and the reverse can also wash out gains. One step often dominates and the other adds little. If a hybrid is tried, test with and without each step and keep only what lifts the target score.
A workable split discussed in class keeps stemming on long documents for index terms and lemmatization on short queries for sense. Both sides still meet in one shared space at match time, but each side uses the tool that suits its shape. Documents are long and many, so cheap stems help. Queries are short, so careful sense analysis pays off. The shared space still needs one common mapping, so test that the pair truly meets instead of assuming it.
Scope: split pipelines fit document-heavy collections with short queries. Assumption: both sides land in one shared term space. If the stem space and the lemma space diverge, matches fall apart and one side must change.
Never stack blindly. Ablate each step, keep only what lifts the score, or split the work with stems for documents and lemmas for queries.
4.5.3 Collection Size and Cost
When the document count runs into millions, compute cost pushes toward stemming. Each document pays the analysis cost once, but millions of documents turn a small per-word cost into a large bill. When the collection is of a size that is easy to manage and exact match matters, lemmatization is worth the cost. The pick is a trade between compute budget and need for exact sense. Query load matters too: a small collection with heavy query traffic can still favor cheap index forms.
Picture a chart with collection size on the horizontal axis and total analysis cost on the vertical axis. Two lines rise from the origin: a shallow line for stemming and a steep line for lemmatization. The gap between them is small at the left and wide at the right. The takeaway is that size multiplies the per-word cost gap, so large collections feel the choice most.
Size multiplies cost. Millions of documents push toward stems, while small exact-match collections repay lemmas.
4.5.4 Student Questions and Answers
Q: After stemming, why not just run lemmatization on the stems to fix them?
A: Fixed stems are often too broken to fix. A stem such as gen could map to gene or generation, and easy still maps to easy, so the second step guesses. Test the stack. In most cases one careful step beats two stacked steps.
A second doubt asked for a concrete case where both appear.
Q: Can you give a case where both are used, since stacking seems pointless?
A: Many published pipelines list both. Often the listed order is lemmatization first and stemming after, or the reverse. The effect of one step is then far smaller than the effect of the other. Teams copy full pipeline blocks without checking. A cleaner split is stemming for index terms and lemmatization for query sense, with checks that the pair truly helps.
A third doubt tested the size rule itself.
Q: Is it right that huge collections push us to stemming while small collections allow lemmatization?
A: Yes, as a first guide. With millions of documents, cheap stems save much compute. With a smaller set where exact match matters, pay for lemmatization. Still test, since query load and quality goals also shape the pick.
With terms settled, the lecture turns from words to the lists that store them.
4.6 Postings Lists, Merge Algorithm and Skip Pointers
4.6.1 Postings in Sorted Order
How does an engine find every document with a word without scanning all text? It looks the word up in a table.
Searching raw text for each query would scan millions of documents per question. An index built once lets each query jump straight to the right documents.
A postings list (the list of document numbers holding one term) pairs each term with its document IDs. A tiny sketch is Brutus pointing to 1, 2, 4, 5. Each ID names one document holding Brutus. Document IDs stay in sorted order. Sorted order speeds merging and all later search steps, because both lists can walk forward together with no backtracking.
Think of two sorted attendance rolls. To find pupils on both rolls, two fingers walk down together. No finger ever moves back up. The analogy breaks where skips enter: fingers cannot jump pages, but postings lists can.
Each term points to its documents in sorted ID order. Sorted order is what makes every later merge fast.
4.6.2 Merge for AND Queries
An AND query such as Brutus AND Caesar needs IDs present in both lists. The plain merge walks both sorted lists from the start. Call the list lengths and , where and are counts of IDs. In plain words, the number of ID checks grows with the sum of the two lengths. In symbols:
Here is time cost, is the first list length, and is the second list length. The walk compares the two heads. Equal heads join the answer and both sides step. A smaller head steps its own side forward. Each step consumes at least one entry, so the total steps stay linear in the sum of the lengths.
Take Brutus pointing to 1, 2, 4, 5 and Caesar pointing to 2, 4. Compare 1 with 2, step the first side. Compare 2 with 2, record 2, step both. Compare 4 with 4, record 4, step both. Bold answer: the shared documents are 2 and 4. Sense-check: both IDs sit in both lists, and no other ID does.
Plain AND merge costs order of m plus n. Every entry is visited at most once per list.
4.6.3 Skip Pointers in One Paragraph
Skip pointers (forward jumps placed along a postings list) let the merge leap over blocks that cannot hold a match. The pointers are laid down at index time over the sorted lists. When one head is smaller, the code can jump that list ahead instead of stepping one by one. Jumps skip checks that are known to be useless because both lists are sorted. The guard keeps jumps safe: a jump fires only while the landing ID is still not past the other head. Skip pointers help AND queries, where both sides must agree. They do not help OR queries, where every entry from both sides is needed anyway.
Skip guard: with and for the two list heads, follow the skip on the smaller side only while its landing still does not pass the other head:
Here reads the document number at a pointer. When the landing would pass the other head, refuse the jump and step one entry instead.
Scope: skips pay off on long static lists with AND queries. Assumption: the index changes slowly, so pointers laid at build time stay valid. Fast-changing lists break that assumption and can make skips useless.
Skips are pre-built shortcuts for AND merges. The landing guard decides jump or step, so no shared ID is ever leapt over.
4.6.4 Small Walkthrough
Take Caesar heads at 1 and Brutus heads at 2. The heads differ, so the smaller side moves. With a skip in place, the 1 jumps straight to 5. Now the compare is 5 against 2. The 2 side is smaller, so it jumps. The new compare is 5 against 16. Step by step, equal heads join the answer and smaller heads jump or step. The skipped IDs between jumps are never checked one by one. Each jump in this walk fired only because its landing still sat at or below the other head.
Picture the two lists as parallel number lines with curved arrows for skips. The horizontal axis on each line is document ID in sorted order. Each arrow starts at one ID and lands several slots ahead. The takeaway is that arrows bridge the dead bands where no match can hide, so the walk touches only a few heads.
The small walk shows the whole idea: compare heads, jump the smaller side while the landing stays safe, record equal heads.
4.6.5 Student Questions and Answers
Q: Does skipping risk missing a true match between jumps?
A: The method guards the jump. Before a jump, the code checks the landing ID against the other head. A jump happens only when the landing ID is still not past the other head. When the landing ID would pass the other head, the code steps one by one instead, so no shared ID is lost.
A second question set the class list against production scale.
Q: What does a web search engine such as Google do at this stage?
A: Production pipelines add more steps around the same core. They use stop-word handling, indexing, normalization, tokenization, lowercasing, and either stemming or lemmatization. They also normalize accents such as resume forms, split compound words such as a long German word for compute power, and normalize number forms. The class list is a subset, and production systems extend it.
The small walk now grows into a full intersection with matches to count.
4.7 Skip Pointer Full Intersection
4.7.1 How Many Skips to Place
Where should the jumps sit? Too many jumps mean constant guard checks. Too few mean long dead bands with no bridge.
The class rule of thumb balances those two costs with one square root. It is a habit that works well in practice, not a law of nature.
When the test or index gives skip positions, use them. When no positions are given, use the square-root rule. In plain words, take the length of the longer list, take its square root, and round up to set the gap. With for the longer list length and for the skip gap:
Here is a count and is a count of entries between skips. The worked class list held about 16 entries, so the gap was 4. Each 4th entry carried a forward pointer. Place skips on the longer list and probe with the shorter list. When both lists share the same length, either list can carry the skips after sorting.
For , the gap is the ceiling of the square root of 16, which is 4. Entries 1, 5, 9, and 13 carry forward pointers. Bold answer: gap 4. Sense-check: 16 entries split into 4 jumps of 4, so each jump bridges a short band that is cheap to verify.
Exam note: if skip positions are given, use them. If not, use the square-root gap rounded up. State the gap before the walk.
4.7.2 Worked Intersection With Matches 3, 5, 89, 97 and 100
The longer list held 16 IDs and the shorter list held 8 IDs. Plain merge would need up to 24 head-to-head checks, since . In symbols:
Here is check count. Skips cut that count.
The walk ran like this. Compare 3 with 3. They match, so 3 joins the answer. Move to 5 with 5. They match, so 5 joins the answer. Next compare 9 with 89. The first head is smaller, so check the landing. The first landing is 24. Since 24 is still less than 89, jump to 24. Compare 24 with 89. Still smaller, so jump to 75. The stretch of IDs between 9 and 75 on the upper list is never checked one by one. That is the whole gain.
Now compare 75 with 89. The first head is still smaller. Look at the next landing, 92. Since 92 is greater than 89, the jump is refused. The code falls back to stepping. It checks 81 with 89, then 84 with 89. No match. Then 89 with 89 matches, so 89 joins the answer.
Move past the match. Compare 92 with 95. The first head is smaller. The next landing is 115. Since 115 is greater than 95, the jump is refused again. Step to 96 with 95. The first head is greater, so move the second list. Then 97 aligns with 97, so 97 joins the answer. Step to 100 with 99. Move the second list. Then 100 with 100 matches, so 100 joins the answer. Close with 115 against 101. No match.
Final answer list is 3, 5, 89, 97, and 100. The count of head checks is well below 24. There is no fixed closed form for skip cost. It depends on the actual IDs, so count the checks for the given lists.
Exam note: plain merge cost is order of m plus n. For 16 and 8, that is 24 checks. Skip search needs a manual count. There is no fixed formula to quote. Show the count dropping below 24 by hand.
4.7.3 Skip Pseudocode Shape
The skip merge matches plain merge except for one block. When the first head is smaller and a skip landing exists, check the landing against the second head. When the landing is still not past the second head, jump. When it would pass, step to the next ID. That guard is the only change. It is the step that keeps the method safe.
The procedure runs like this. Start with both heads at the first entry. At each round, compare heads. On a match, record the ID and step both sides. On a mismatch, test the smaller side for a safe jump. Jump while landings stay at or below the other head, then step once. Repeat until one list runs out. Skips exist only on the original built lists; middle results of a longer query carry no skips.
Scope: the guard block is the only addition to plain merge. Assumption: both lists stay sorted and skips were built over them. Unsorted input or per-query rebuilt skips break the logic.
One guard block turns plain merge into skip merge. Everything else stays the same.
4.7.4 Small Book Exercise
A second book exercise used 16 entries on one side and 1 entry on the other. Plain merge needs 17 checks. With a gap of 4 from the square root of 16, the target is reached in about 6 checks by hopping 4 by 4. Walk the long list in jumps of 4 while each landing stays at or below the single target ID, then step through the last short band. Readers can replay the hops to see the count drop from 17 to about 6.
One entry against 16 shows the best case: jumps bridge almost the whole list and only the final band needs steps.
4.7.5 Student Questions and Answers
Q: Are skip pointers fixed once at build time from the first entry onward?
A: Yes. Skips are laid down over sorted lists before search, often each 4th entry in the class example. At query time the merge only follows them. It does not rebuild them per query.
On equal lengths, the next doubt followed.
Q: When both lists have the same length, which one carries skips?
A: Either list can carry them once sorted. Pick one as the jumping list and the other as the probe list. The logic stays the same.
On the refused jump at 75 against 89, the next doubt followed.
Q: After 75 against 89, why step instead of jumping to 92?
A: Because 92 is already past 89. Jumping would leap over the band where 89 could still match, such as 81, 84, and 89. The guard refuses the jump and the code steps so the band is checked.
Past the 89 match, the walk continued into fresh doubts.
Q: After 89 matches 89, what comes next with 92 and 95?
A: Compare 92 with 95. The first head is smaller, so test the 115 landing. Since 115 is past 95, refuse the jump and step. Then 96 against 95, then moves on the second list until 97 matches 97 and 100 matches 100.
A last doubt asked what the test truly demands.
Q: Do we need to memorize this pseudocode for the test?
A: Exam note: no pseudocode writing is asked. Implementation of the idea can be asked. As a masters class, the code shape is assumed known, but writing out full pseudocode from memory is not the test goal.
Fast ID lists now give way to word order: phrases need more than single terms.
4.8 Phrase Queries and Biword Indexes
4.8.1 Why Single Terms Fail Phrases
A phrase query needs exact order. Stanford University as one school is not the same as the two words Stanford and university spread across a sentence.
Two texts can both hold Stanford and university yet deserve very different scores. One text holds the phrase. The other holds something like the inventor at Stanford never went to university, with the words apart and in odd order. Term-only matching scores both texts too much alike.
Order must enter the index. Without it, distance and sequence carry no weight, and spread-out words pose as phrases. The fix stores word pairs or word positions alongside single terms, so order becomes checkable at query time.
Single terms cannot see order. Phrase truth needs pairs or positions in the index.
4.8.2 Biword Index
A biword index (an index over neighboring word pairs) stores pairs in order. For I have friends Romans countrymen, the pairs are I have, have friends, friends Romans, Romans countrymen, and so on in sequence. A query for Stanford University then looks up the pair Stanford University, not the two single words. Only texts with the words side by side score.
Cut Stanford University Palo Alto into pairs: Stanford University, University Palo, and Palo Alto. The first and last pairs read well. The middle pair University Palo has little sense on its own. That slicing is a known weak point of cutting long phrases into pairs. Still, for short phrases and for Boolean pairs with AND, OR, and NOT, biwords help and keep lookup simple. Bold answer: biwords fix two-word phrases and strain on longer ones. Sense-check: each pair lookup is one exact key fetch, so short-phrase search stays fast.
Longer phrases are cut into pairs and each pair is looked up on its own. The middle pairs can mislead, but the method stays cheap because no position lists are stored.
Biwords store ordered neighbor pairs. They answer short phrases with fast exact lookups and slice long phrases into awkward middle pairs.
4.8.3 Extended Biwords With Word Classes
Extended biwords (class-filtered pairs) first label words as nouns, prepositions, and similar classes, then form pairs across classes. Take cost overruns on power plant. After labeling nouns and prepositions, kept pairs look like cost overruns, overruns power, and power plant in simplified bigram shape, shaped by noun and preposition slots. The cross-product across classes keeps more useful pairs and drops some noise. It can lift accuracy over raw pairs because grammatical junk pairs never enter the index.
Think of sorting mail by street before pairing houses. Raw pairs join any two neighbors. Class-filtered pairs join only neighbors from useful streets. The analogy breaks where grammar is fuzzy: wrong labels drop good pairs.
Label first, pair second. Class filtering keeps the useful pairs and drops grammatical noise.
4.8.4 Limits: False Hits and Index Growth
Biwords still return false hits. A query for blue house can match the sky was blue house was dark. The words blue and house sit side by side across a sentence break, but the sense is wrong. That is a false positive from pair matching: adjacency without sentence truth.
Scope: biwords suit short phrases and fast approximate search where some error is fine. Assumption: neighboring words belong together. Sentence breaks, lists, and odd word order break that assumption and create false hits.
Biwords also grow the dictionary. Single-word entries stay, and pair entries are added on top. Pairs such as the sky, sky was, was blue, blue house, house was, and was dark all need space. The index gets much larger for a gain that is only partial. Each new pair is a new key with its own postings, so vocabulary growth multiplies storage.
Picture a bar chart of vocabulary size. The horizontal axis shows index type: single terms, biwords, positional. The vertical axis shows key count. The biword bar towers over the single-term bar. The takeaway is that pairs buy phrase power with vocabulary growth.
Real-world: biwords suit short phrases and fast approximate search where some error is fine. When exact phrase match is a must, positional data is needed instead.
Two traps to avoid. One is trusting pair hits as exact phrase hits. The other is indexing every pair on a huge collection without budgeting the space.
Pairs bring false hits across sentence breaks and a much larger dictionary. They are an approximate tool, not an exact one.
4.8.5 Student Questions and Answers
Q: If biwords slice long phrases into odd pairs, why use them at all?
A: They are cheap and help short phrases and Boolean pair queries. For longer phrases or strict order needs, move to positional indexes. Use biwords when approximate answers are fine and index labor must stay low.
Exact phrase truth needs full positions, which come next.
4.9 Positional Indexes and Phrase Exercise
4.9.1 What Extra Data Is Stored
What if the index remembered every word place? Then phrase checks become number checks.
Pairs guess at order. Positions record it. That record costs space, and for exact phrases it is worth paying.
A positional index (a term map with per-document positions) stores for each term its total count, then per document the document ID, the in-document count, and the full position list. The spoken sketch for the word numbered 2 listed a total near 3427, then blocks such as 6 hits in the first document at positions 7, 18, 33, 72 and more, 5 hits in the second document at its own positions, and further blocks after. The point is that every hit knows its place: term, document, count, and slot list.
Positional entry shape: term, then total hit count, then one block per document holding the document ID, the hits inside that document, and every position number. No step in that chain can be skipped at build time.
Positions turn the index from a bag of words into a map of word places. Building it costs more, and exact phrases need it.
4.9.2 How Phrase Match Uses Adjacency
With positions, a phrase check is a numbers check. Take data seen in document 1 at positions 3 and 10, and science seen in document 1 at positions 4 and 11. In plain words, science sits one slot after data in both spots. In symbols, with for a position of the first word:
Here is a word slot number starting at 1. Pairs 3 with 4 and 10 with 11 both pass. Document 1 is a true hit for data science. No false hit from spread-out words can pass, since spread-out words do not sit in consecutive slots.
Test document 1 against data science. Read data slots 3 and 10, read science slots 4 and 11. Check 3 plus 1 equals 4, which passes. Check 10 plus 1 equals 11, which passes. Bold answer: document 1 holds data science twice. Sense-check: both hits are consecutive slots, so no sentence break can hide inside them.
Common phrase queries such as data science, data mining, Stanford University, and information retrieval are handled this way with no pair-sense loss. Longer phrases extend the same check: each next word must sit exactly one slot after the last.
A phrase of length k needs k consecutive slots. Read the lists, add one per step, and keep only documents where the run holds.
4.9.3 Worked Exercise: Fools Rush In
The exercise asked which documents hold fools rush in as three words in a row. Position blocks were read for fools, rush, and in.
Document 4 showed 8, 9, and 10 across the three words, so document 4 holds the run 8 then 9 then 10 and is a hit. Document 2 showed 1, 2, and 3 in order, so document 2 is a hit. A third candidate near 3, 4, and 5 was also accepted in discussion as a hit for the same reason. Bold answer: documents 2 and 4 hold fools rush in, plus the 3-4-5 candidate. Sense-check: each hit shows three consecutive slots across the three words, which is exactly the phrase shape.
Three-word phrases need three consecutive slots. State the document, each word, and each slot number.
4.9.4 Worked Exercise: Angels Fear to Tread
The second phrase was angels fear to tread, a four-word run. Read the four position lists together.
Document 4 showed 12, 13, 14, and 15 in order, so document 4 is a hit. Document 2 lacked the needed run, since its fear and tread slots did not follow angels by one each. One list showed fear starting near 87 and tread starting near 47, which cannot form 36, 37, 38, and 39, so that document fails. Document 7 showed angels at 17 and fear at 18 but the next slot was 19 in a mismatched shape, and the tread slot did not line up, so document 7 was dropped after rechecking. A side note said that changing a misread 199 to 19 would change the call for document 7, but the class kept the numbers as printed and left document 7 out. Bold answer: only document 4 holds angels fear to tread. Sense-check: 12 through 15 is a clean run of four, and no other document shows one.
The AND of the two phrase sets keeps document 4. That is the only document holding both fools rush in and angels fear to tread in exact runs.
Scope: positional checks give exact phrase truth. Assumption: slot numbers were built over the same token stream as the query. A mismatch in tokenization or stop-word handling shifts every slot and breaks the runs.
Exam note: for a phrase of length k, show k consecutive slots. State document, word, and slot numbers for each step, then AND the phrase sets.
4.9.5 Student Questions and Answers
Q: Why is the positional index called a favorite despite the extra work?
A: Because it removes the false hits that pair indexes keep. The extra labor is building full position lists per document. When exact phrase truth matters, that labor pays off.
Positions settle phrases. The next structure speeds up the dictionary itself.
4.10 Hash Table Dictionaries
4.10.1 What the Dictionary Holds
Every query starts with one question: is this term even in the collection?
Before any postings merge or phrase check, the engine must find each query term and fetch its list. That lookup happens millions of times a day, so its speed sets the floor for everything else.
A dictionary (the term table for retrieval) maps each term to its document count and its postings. A small money sketch used 20 bytes for terms, 48 bytes for document counts, and 48 bytes for postings. Those byte counts show why memory shape matters once the vocabulary grows. Small per-term costs multiply across hundreds of thousands of terms. For each query, the first job is to check whether each query term exists and then fetch its postings.
The dictionary is the front door of retrieval. Term lookup speed and memory shape bound the whole system.
4.10.2 How Hash Lookup Works
A hash table (a one-shot address map) stores each term at an address set by a hash function (a rule from word to slot number). A simple classroom sketch takes letter codes such as ASCII codes, sums them, and takes mod 5 or mod 7 to get the slot. Apple might live at slot 005. At search time the same function runs on apple and the code goes straight to 005. Case folding first maps Apple to apple so both meet at one key.
In plain words, one computation finds the term. In symbols, with for the term, for the hash function, and for the address:
Here is a string, is a function from strings to slot numbers, and is an integer slot. Until that slot is cleared, no other term takes it. Lookup cost is order one. In symbols, with for time and for vocabulary size:
Here is lookup time and is the count of terms. The cost does not grow with vocabulary size. One hash plus one fetch returns the postings, whether the vocabulary holds ten thousand terms or ten million.
Store apple at slot 005 by summing its letter codes and taking the remainder mod 7. Query apple later: sum the same codes, take the same remainder, land on 005, fetch the postings. Bold answer: one computation reaches the term. Sense-check: the same input always yields the same slot, so the term is always found where it was stored.
Hash lookup costs order one. One function call maps any term straight to its slot.
4.10.3 Where Hash Tables Fall Short
Hash tables need exact keys. Pairs such as judgement with and without the middle e, or color in United States spelling against colour in British spelling, live at different slots. A query for one form misses the other. Prefix search fails too. A query for comput with a star should bring compute, computer, computing, and computation, but a hash table has no prefix branch to walk. A query for auto with a star should bring automatic, automobile, autonomous, and more, yet hash slots give no help. Small typos also miss, since one wrong letter hashes far away. When the vocabulary keeps growing, the table must be rebuilt by rehashing, which costs much time and space.
Scope: hash lookup fits exact search where speed is the top goal and queries are clean. Assumption: query terms arrive in stored form. Variant spellings, typos, and star queries break that assumption and need ordered structures instead.
Picture a wall of numbered mailboxes with no street order. Knowing the exact box number reaches a letter in one step. Asking for all boxes on one street fails because the wall keeps no street order. The takeaway is that hashes give speed by giving up order.
Real-world: hash lookup fits exact search where speed is the top goal and queries are clean.
Three traps to avoid. One is skipping normalization and stranding variants at separate slots. Two is asking a hash for prefix matches it cannot walk. Three is letting the table fill until every insert triggers a costly rebuild.
Hashes trade order for speed. Exact keys fly, while variants, typos, and stars need trees.
4.10.4 Student Questions and Answers
Q: Why does a hash table miss judgement against judgment or color against colour?
A: Because each spelling hashes to its own slot. The table checks equality of keys, not likeness of sense. Without a shared normalized key, the two forms never meet.
Ordered trees recover what hashes give up, and they come next.
4.11 Tree Dictionaries: Binary Search Trees and B-Trees
4.11.1 Why Trees Help Retrieval
What if the dictionary kept alphabetical order? Then whole branches could be skipped or read at once.
Hashes answer one exact key fast. Trees answer whole neighborhoods of keys: all words with one prefix, all words in one band, all words around one stem.
Trees keep terms in sorted order down branches. That order gives two wins. Prefix and wildcard search become branch walks. Large vocabularies can be searched by skipping whole branches. A school analogy from class makes the point. With the school as root, classes one to five on the left and classes six to ten on the right, a search for tenth-grade marks can skip the full left half. Tree search skips in the same way: one branch choice drops half the vocabulary at once.
Order is the feature. Sorted branches turn prefix search into a walk and let whole unrelated bands drop in one step.
4.11.2 Binary Search Tree Walk
A binary search tree (a two-branch sorted tree) sends alphabetically smaller terms left and larger terms right. A class example sent A to M left and N to Z right from the root. Deeper nodes split again, such as A to H left and later letters to M right on one side. To find hygiene, start at the root, go left for the H range, then left again as the range narrows, and keep moving till the word is reached. To find a word on the right side, go right, then right, then left and left as the ranges direct. Each move drops many untouched branches at once. That is why even a large vocabulary can be searched fast and with correct order.
Lookup cost grows with tree height, not in one step. In plain words, cost grows with the log of vocabulary size. In symbols, with for time and for term count:
Here is lookup time and is the count of terms. It is slower than hash order one, but it keeps order, prefix search, and wildcard search. Doubling the vocabulary adds only one level, so growth stays gentle.
Find hygiene in the class tree. Start at the root split A to M against N to Z. H sits in A to M, so go left. At the A to H against later-to-M split, H sits in the left band, so go left again. Keep narrowing until hygiene is reached. Each step drops a full band of terms. Bold answer: left, left, then narrow to hygiene. Sense-check: H never leaves the left half until the bands force finer moves, so no step wastes work.
Binary search costs order log M. Each level drops a full band, which buys order and prefix power for a small speed cost.
4.11.3 Skew and the Move to B-Trees
Simple binary trees skew when many terms share early letters. Names starting with S can pile on one side and make that side deep. Search then slows because height grows on one side while the other side sits empty. A B-tree (a multi-branch balanced tree) lifts the two-branch limit. Each node is allowed a range of branches, such as 2 to 4 branches per node. In symbols, with for branch count of a node:
Here is a plain count. One node can guide to several letter bands at once. Height drops, memory for the shape drops, and fewer levels mean quicker fetches. The letter B has no single agreed expansion in class. Bayer from a name, broad, and balanced were all mentioned. Balanced fits the use here, since the goal is to fix skew.
Scope: B-trees fit large vocabularies on slow storage, where each level can cost a disk read. Assumption: terms spread across bands so nodes stay within their branch range. Heavy skew with no rebalancing breaks that assumption and depth grows again.
More branches per node means fewer levels. B-trees stay shallow where binary trees skew deep.
4.11.4 Prefix Search on Trees
Prefix search is a branch read. A query for hyp with a star walks to the hyp branch and reads off hyper, hypothesis, hypertext, hyperlink, and related forms. A query for auto with a star reads automatic, automobile, autonomous, and more from the auto branch. Hash tables cannot do this since they keep no lexical order. Trees keep that order, so the branch holds the answer. One walk plus one branch scan returns the full set, which then feeds the normal inverted index for document lookup.
Answer auto with a star. Walk from the root down the a-u-t-o path to the auto node. Read every term below it: automatic, automobile, autonomous, and the rest of the branch. Bold answer: the branch below auto is the answer set. Sense-check: every stored word starting with auto sits below that node, and no other word does.
Real-world: tree dictionaries suit large vocabularies that must be read in sorted order and that need fast prefix and wildcard paths plus richer query steps.
Stars become branch reads. Walk to the prefix node and collect the branch.
4.11.5 Rebalancing Cost
Trees need care when terms leave. If the only word in the H-to-M band is rare and is removed, that edge and node vanish. A binary tree must then reshape parent and child links or some terms in that band lose their path. That reshape is costly when the dictionary is large and changes often. B-trees soften the pain because the branch count is a range, not a strict two. Imbalance only bites when a node drops below the low end of the range, such as below 2 in a 2-to-4 tree, which happens rarely. Most deletions leave the shape valid with no rebuild.
Deletion forces reshapes in strict binary trees but rarely in B-trees, where the branch range absorbs most changes.
4.11.6 Student Questions and Answers
Q: Why are trees better than hash tables here if hash tables are faster?
A: Trees keep sorted order and branch shape. That gives prefix match, shared stems on one branch, and full skips of unrelated branches. Hash tables win on raw speed for exact keys but give no prefix path and no order walk.
On the hygiene walk itself, the next doubt followed.
Q: For hygiene, which way do we go at the root in the A-to-M against N-to-Z split?
A: Go left, since H sits in A to M. Then keep comparing subranges such as A to H against later letters to M and move left or right as each band directs until the word is reached.
On the name itself, a last doubt followed.
Q: What does the B in B-tree stand for?
A: No single expansion was fixed in class. Bayer, broad, and balanced were mentioned. Balanced is a useful reading here because the shape fixes skew in binary trees.
Trees handle trailing stars well. Leading stars need one more trick.
4.12 Wildcard Queries and Reverse Trees
4.12.1 What Tolerant Retrieval Means
Real queries are messy. That fact, not clean textbook input, drives this whole block.
Users mistype, mix spellings, drop endings, and paste foreign words. An engine that demands perfect input fails its most human users.
Tolerant retrieval (search that bears with human slips) drops the hope that every query is typed well. Real queries hold spelling slips, variant spellings, missing parts, and foreign marks. The index must still bring the right texts. Lenses for tolerance are wildcard queries, spelling handling and sound-based fixes, plus accent and variant handling. Wildcards come first because trees already support half of them.
Tolerance means answering the query the user meant, not only the string they typed.
4.12.2 Star Queries
A wildcard query (a query with a star for any tail) uses the star learned from database search, where select all uses a star for all. A query for mon with a star should bring money, monitor, month, monkey, and more such as month forms. In plain words, keep words that start with mon and sit below moo. In symbols, with for a dictionary word:
Here is a string and the bounds are strings in lexical order. The upper bound moo comes from stepping the last prefix letter one step forward, from n to o, which closes the mon band tightly. The wanted words money, monitor, month, and monkey pass. Motor and moon do not pass, since they sit outside the band: motor breaks at the third letter and moon breaks at the second.
Test the small demo set of monitor, money, month, monkey, motor, and moon against mon with a star. Money, monitor, month, and monkey all start with mon and sort below moo, so all four pass. Motor fails at the third letter since t sorts past n. Moon fails at the second letter since o sorts past n at that slot. Bold answer: money, monitor, month, and monkey match; motor and moon do not. Sense-check: every kept word starts with mon and every dropped word breaks the prefix early.
Spelling pairs such as Sydney variants, color against colour, and judicial against judiciary show why stars help. When the exact stored form is unsure, a shaped star such as sydney with a star inside, judicia with a star at the end, or color variants can still pull both forms. Foreign-name queries such as a university name with an unsure middle work the same way.
A trailing star is a band query. Name the tight band, keep what falls inside, and drop what breaks the prefix.
4.12.3 Trailing Stars Are Easy, Leading Stars Need Help
Trailing stars fit B-trees well because the tree is already in lexical order. Walk to mon and read the branch. Leading stars do not fit. A query for words ending in mon, such as common and lemon, has no shared front branch to walk, since the shared letters sit at the tail.
The fix is a reverse B-tree (a tree over reversed spellings). Lemon is stored backwards in reversed letters, and common is stored backwards in the same reversed way. A leading-star query is then flipped to a trailing-star query on the reversed tree: reverse the pattern, walk the reversed tree, read the branch. Search becomes a normal branch read again, only backwards. Queries with a star in the middle split the work: the front part walks the normal tree, the tail part walks the reversed tree, and the two sets meet in an AND.
Scope: two trees cover queries with one star anywhere. Assumption: the reversed tree is built and kept in step with the normal one. A stale reversed tree silently drops valid endings.
Front stars walk the normal tree, tail stars walk the reversed tree, and middle stars use both with an AND.
4.12.4 Student Questions and Answers
Q: What should mon with a star return on the small demo dictionary with monitor, money, month, monkey, motor, and moon?
A: It returns money, monitor, month, and monkey. It leaves out motor and moon because those words sit outside the mon to moo band.
One star in any spot still needs many structures. The next index folds every star shape into one lookup.
4.13 Permuterm Index With Rotations
4.13.1 The End-Marker Idea
What if every star shape became a trailing star? Then one lookup shape would cover all queries.
Normal plus reversed trees need two structures and an AND for middle stars. A rotation index pays more space to make every query a single branch read.
A permuterm index (a rotation index for wildcards) adds an end-marker to each word and stores all rotations of that marked word. The marker was spoken as dollar in class and is written here in words only to keep the text plain. Start with hello with the marker at the end. Then move the first letter to the end, step by step, till the marker moves round the full circle. The rotation set reads: hello followed by the marker, ello followed by the marker plus h, llo followed by the marker plus he, lo followed by the marker plus hel, o followed by the marker plus hell, and the marker followed by hello. All six forms enter the rotation vocabulary, one per letter plus one for the marker. The count of stored forms grows with word length, so longer words cost more rows.
Per word, store every rotation of the word plus its end-marker. Each rotation links back to the source word. The rotation vocabulary is large, but every star placement gets a rotated form that ends with the star.
Rotations trade space for lookup shape. More rows per word buy one uniform query form.
4.13.2 How Rotations Turn Any Star Into a Trailing Star
The rotation set lets any star query become a trailing-star query. Take a shape such as m with a star then n. Rotate the query so the star sits at the end, giving n with the marker plus m plus a trailing star. Look up that rotated prefix in the rotation vocabulary with a trailing star. The hits point back to source words whose rotation matches, such as man and moron for that shape. Leading stars, trailing stars, and middle stars all map to one trailing lookup this way. That single-shape lookup is the whole point of the rotation build. Queries with two stars need an extra filter pass: look up the first star shape, then check each candidate for the middle string, keeping hits like fishmonger and dropping misses like filibuster for a shape with mo in the middle.
The price is dictionary size. Every term contributes as many rotations as it has characters plus one, so the rotation vocabulary dwarfs the source vocabulary. The index links each rotation back to its source term, and source terms then feed the normal inverted index for document lookup.
Trace hello plus the end-marker through all six rotations: hello marker, ello marker h, llo marker he, lo marker hel, o marker hell, marker hello. Each rotation links back to hello. Now answer m star n: rotate the query to n marker m with a trailing star, read that branch in the rotation vocabulary, and map hits back to man and moron. Bold answer: six rotations stored, one trailing lookup answers the query. Sense-check: each star placement owns a rotation that ends with the star, so no shape needs special code.
Scope: permuterm indexes fit single-star queries of any placement with one lookup. Assumption: the rotation vocabulary fits in fast storage. Very long terms and huge vocabularies strain that assumption and push toward gram indexes instead.
Rotate the query so the star lands last, read one branch, map rotations back to source words, then fetch documents.
Class closed at this point, with the next session set to start from the permuterm index and move on.
4.13.3 Student Questions and Answers
Q: Why store so many rotated forms for one word?
A: So each possible star placement has a rotated form that ends with the star. Then every wildcard shape reduces to one easy trailing lookup instead of many special cases.
That rotation trick closes the lecture arc from word forms to tolerant lookup.
Exam Guidance Summary
Exam note: Porter rules need conditions, not just cuts. State the m-greater-than-one style guard and the short-word block such as cement before the replacement. Name the ending, name the guard, then give the shortened form.
Stemming questions reward the guard first and the cut second.
Exam note: when skip positions are given, use them. When they are not given, use the square-root gap on the longer list and round up. For 16 entries the gap is 4. State the gap before starting the walk.
Skip questions start with placement and continue with a hand-counted walk.
Exam note: plain merge cost is order of m plus n. For 16 plus 8 that is 24 checks. Skip cost has no fixed formula. Count the head checks by hand, show the landing guard at each jump, and show the total below 24.
Implementation understanding beats memorized code lines.
Exam note: pseudocode writing is not asked. Implementation of skip merge, biword use, and positional phrase checks can be asked. Know the guard logic and the lookup shapes rather than memorized code lines.
Phrase answers live or die on slot numbers.
Exam note: phrase proofs need slots. For a phrase of length k, show k consecutive positions with document, word, and slot numbers for each step. Then AND the phrase sets across phrases.
Wider context rounds out the marks.
- Exam note: a discussion task asks for recent stemming and lemmatization methods and how they beat the classroom methods. Join that thread since it helps with NLP preprocessing choices. Compare on speed, match quality, and language coverage.
- Exam note: hash cost is order one for exact lookup. Tree cost is order log M for M terms. Trees add prefix and wildcard power at that extra cost. State both costs with the trade between them.
Key Industry Applications
Production search stacks combine every step of this lecture. Stop-word handling, normalization, tokenization, lowercasing, and stemming or lemmatization run in order on web scale. Accent handling folds variants such as resume forms to shared keys. Compound splitting breaks long German-style compounds into searchable parts. Number handling maps alternate digit forms together. Google-style pipelines use all of these because each step removes one class of mismatch between queries and documents.
WordNet from NLTK gives a common lemmatizer baseline in Python. Teams start there to get sense-aware base forms with little setup. SpaCy ships a lemmatizer used in many pipelines where speed and pipeline fit matter more. Stanford tools and TextBlob give more lemmatizer options to test when accuracy or language coverage needs a check.
Snowball supports many languages for stemming where Porter is English-only. Mixed-language collections pick per-language Snowball tables instead of forcing English rules everywhere.
Prefix search such as auto with a star powers type-ahead and database-style wildcard find. Each keystroke walks one level deeper and reads the branch below. The SQL-style star for all motivates the wildcard star habit that users bring from databases.
Positional indexes power exact phrase search such as data science and Stanford University without false hits. Legal, news, and academic search pay the position storage cost because a wrong phrase hit costs more than the space. Biword indexes power fast approximate phrase match where some false hits are fine, such as quick first-pass retrieval before a careful rerank.
Skip pointers speed AND merges over long sorted postings in production indexes. Long static lists carry pre-built jumps, and the merge guard keeps every jump safe at query time.
Each lecture idea maps to one production part: normalization and splitting for mismatch removal, lemmatizers and Snowball for language sense, positions and biwords for phrases, trees and skips for speed.
IR Lecture 4 notes · Stemming, Skip Pointers, Phrase Search and Tolerant Retrieval
Sections Breakdown
Preprocessing recap: tokenization, normalization, and stop-word handling form one shared chain, and over-removal empties lines like to be or not to be
Porter stemming applies conditioned longest-suffix rules in phases; the m-greater-than-one guard blocks short words like cement while mapping replacement to replac
Lovins, Paice-Husk, and Snowball compared: single-pass longest-suffix cuts, aggressive iterative cuts, and multilingual Porter-style rules, tested on one sample passage
Lemmatization keeps real base words through rules, dictionary lookup, and POS tagging, with the bank example showing how tags split river sense from money sense
Stemming versus lemmatization: cheap fast conflation against careful sense, with hybrid order effects and collection-size cost guiding the pick
Postings lists in sorted order, plain AND merge in order m plus n, and skip pointers as guarded pre-built jumps for AND queries
Full skip-pointer intersection: square-root gap placement, worked walk to matches 3 5 89 97 100, pseudocode guard shape, and the 16-plus-1 book exercise
Phrase queries need order; biword and extended biword indexes answer short phrases cheaply but keep false hits and grow the dictionary
Positional indexes store per-document slot lists so phrase checks become adjacency checks; fools rush in and angels fear to tread leave only document 4 in the AND
Hash table dictionaries give order-one exact lookup by address from hash function but miss variants typos and prefix stars for lack of order
Tree dictionaries keep sorted order for prefix and wildcard branch reads at order log M, with B-trees fixing binary skew by allowing 2 to 4 branches per node
Wildcard queries as band queries on B-trees, with reverse B-trees flipping leading stars into trailing branch reads
Permuterm index stores all end-marked rotations per word so leading trailing and middle stars all reduce to one trailing lookup
Exam guidance carried through: Porter conditions, skip gaps and hand counts, no pseudocode writing, slot-numbered phrase proofs, discussion thread, and hash against tree costs
Industry applications carried through: production normalization pipelines, named lemmatizers, Snowball multilingual stemming, prefix type-ahead, positional exact phrases, biword approximate phrases, and skip speedups
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
Preprocessing Recap: Tokenization, Stop Words and Normalization
Must-know: Preprocessing is one fixed chain (tokenize, normalize, stop words, stemming or lemmatization) shared by documents and queries; aggressive stop-word dropping empties lines like to be or not to be
Top pitfall: Tuning rules on one query set and trusting them everywhere, or fixing documents but forgetting queries
Self-check: Why must documents and queries share the same preprocessing chain?
Connects to: 4.2, 4.5
Porter Stemming Rules
Must-know: Porter applies longest-suffix rules in five phases with a measure guard; the EMENT rule maps replacement to replac but leaves cement alone
Top pitfall: Quoting only the shortened word without the condition; short words like cement must stay untouched
Self-check: Why does replacement shorten while cement stays whole under the EMENT rule?
Connects to: 4.1, 4.3, 4.5
Other Stemmers: Lovins, Paice-Husk and Snowball
Must-know: Lovins strips the longest suffix in one pass, Paice-Husk iterates to the shortest stems, Snowball ports Porter style to many languages; test on your own data
Top pitfall: Reading a demo passage as a verdict instead of testing each stemmer on the real collection
Self-check: Which stemmer cuts shortest on the sample passage, and why can it still win in a narrow domain?
Connects to: 4.2, 4.4, 4.5
Lemmatization: Rule-Based, Dictionary-Based, Hybrid and POS Tagging
Must-know: Lemmatization maps words to real dictionary base forms via rules, dictionary lookup, and POS tags; bank needs tags plus neighbors to split river sense from money sense
Top pitfall: Running lemmatization on chopped stems like gen and expecting it to recover gene or generation
Self-check: Why can rules plus a dictionary still pick the wrong lemma for bank?
Connects to: 4.2, 4.3, 4.5
Stemming Versus Lemmatization: When to Use Which
Must-know: Stemming for cheap fast indexing, lemmatization for careful sense; split stems for documents and lemmas for queries, and ablate before stacking
Top pitfall: Stacking stemming plus lemmatization without testing, so one step destroys what the other needs
Self-check: Why does a chopped stem like gen defeat a later lemmatization step?
Connects to: 4.2, 4.4
Postings Lists, Merge Algorithm and Skip Pointers
Must-know: Postings stay sorted; plain AND merge costs order m plus n; skips are pre-built jumps guarded by landing at or below the other head, for AND only
Top pitfall: Jumping without checking the landing against the other head, which can leap over a true match
Self-check: When does the merge jump and when must it step instead?
Connects to: 4.7
Skip Pointer Full Intersection
Must-know: Skip gap is ceiling of square root of longer list length; 16 entries give gap 4; plain merge of 16 and 8 costs 24 checks while skips need a manual count below that
Top pitfall: Quoting a fixed formula for skip cost instead of counting head checks by hand for the given lists
Self-check: Why is the jump to 92 refused when comparing 75 against 89?
Connects to: 4.6, 4.8
Phrase Queries and Biword Indexes
Must-know: Biwords index ordered neighbor pairs for cheap short-phrase search but slice long phrases awkwardly, return false hits like blue house, and grow the dictionary
Top pitfall: Trusting pair hits as exact phrase hits when sentence breaks can join unrelated neighbors
Self-check: Why does the sky was blue house was dark falsely match the phrase blue house under biwords?
Connects to: 4.7, 4.9
Positional Indexes and Phrase Exercise
Must-know: Positional index stores term totals plus per-document IDs counts and slot lists; phrases need k consecutive slots; only document 4 holds both fools rush in and angels fear to tread
Top pitfall: Forgetting that slot numbers depend on the token stream, so mismatched tokenization breaks every run
Self-check: What must you state for each step of a phrase proof of length k?
Connects to: 4.8, 4.10
Hash Table Dictionaries
Must-know: Hash dictionary maps term to address by a equals h of t with order-one lookup; exact keys only, so variants typos and star queries miss
Top pitfall: Asking a hash for prefix or star matches, or stranding variants at separate slots without normalization
Self-check: Why do judgement and judgment never meet in a hash table?
Connects to: 4.11, 4.12
Tree Dictionaries: Binary Search Trees and B-Trees
Must-know: Trees keep sorted order for prefix branch reads at order log M; B-trees allow 2 to 4 branches per node to fix skew; hygiene walks left from the root
Top pitfall: Forgetting that binary trees skew under shared early letters and need B-tree balance to stay shallow
Self-check: Why does auto with a star become a branch read on a tree but fail on a hash?
Connects to: 4.10, 4.12
Wildcard Queries and Reverse Trees
Must-know: Trailing star mon maps to the band mon to moo and returns money monitor month monkey without motor moon; leading stars flip to trailing queries on the reverse B-tree
Top pitfall: Walking a leading star on the normal tree instead of flipping to the reversed tree
Self-check: Why does moon fall outside the mon to moo band?
Connects to: 4.10, 4.11, 4.13
Permuterm Index With Rotations
Must-know: Permuterm adds an end-marker and stores all rotations per word so any single-star query rotates into one trailing lookup
Top pitfall: Forgetting that each term costs as many rotations as characters plus one, so the rotation vocabulary dwarfs the source
Self-check: Why does hello contribute six rotations to the permuterm vocabulary?
Connects to: 4.12
Exam Guidance Summary
Must-know: State Porter guards, square-root gaps, hand-counted skip checks, slot-numbered phrase proofs, and order-one against order-log-M dictionary costs
Top pitfall: Quoting cuts without guards, quoting a fixed skip formula, or proving phrases without slot numbers
Self-check: What must a skip answer state before the walk begins?
Connects to: 4.2, 4.7, 4.9, 4.10, 4.11
Key Industry Applications
Must-know: Production stacks combine normalization plus splitting, WordNet spaCy Stanford TextBlob lemmatizers, Snowball for many languages, positions for exact phrases, biwords for approximate phrases, trees for stars, and skips for AND speed
Top pitfall: Using an approximate tool where exact phrase truth is required
Self-check: When does production search pay for positional indexes over biwords?
Connects to: 4.4, 4.8, 4.9, 4.11
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.