The trie (pronounced as try) is a tree that specializes in storing data that can be represented as a collection, such as English words:
rootCAT.T.E.UTO.B.A trie containing the words CAT, CUT, CUTE, TO, and B
Each string character maps to a node where the last node (marked in the above diagram with a dot) is terminating. The benefits of a trie are best illustrated by looking at it in the context of prefix matching.
In this chapter, you’ll first compare the performance of the trie to the array. Then you’ll implement the trie from scratch!
Example
You are given a collection of strings. How would you build a component that handles prefix matching? Here’s one way:
class EnglishDictionary {
private var words: [String]
func words(matching prefix: String) -> [String] {
words.filter { $0.hasPrefix(prefix) }
}
}
words(matching:) will go through the collection of strings and return the strings that match the prefix.
This algorithm is reasonable if the number of elements in the words array is small. But if you’re dealing with more than a few thousand words, the time it takes to go through the words array will be unacceptable. The time complexity of words(matching:) is O(k*n), where k is the longest string in the collection, and n is the number of words you need to check.
Imagine the number of words Google needs to parse
The trie data structure has excellent performance characteristics for this problem; as a tree with nodes that support multiple children, each node can represent a single character.
You form a word by tracing the collection of characters from the root to a node with a special indicator — a terminator — represented by a black dot. An interesting characteristic of the trie is that multiple words can share the same characters.
To illustrate the performance benefits of the trie, consider the following example in which you need to find the words with the prefix CU.
First, you travel to the node containing C. That quickly excludes other branches of the trie from the search operation:
rootCAT.T.E.UTO.B.
Next, you need to find the words that have the next letter U. You traverse to the U node:
rootCAT.T.E.UTO.B.
Since that’s the end of your prefix, the trie would return all collections formed by the chain of nodes from the U node. In this case, the words CUT and CUTE would be returned. Imagine if this trie contained hundreds of thousands of words.
The number of comparisons you can avoid by employing a trie is substantial.
rootCAIGHJKPT.T.E.UTO.NLMBXY
Implementation
As always, open up the starter playground for this chapter.
TrieNode
You’ll begin by creating the node for the trie. In the Sources directory, create a new file named TrieNode.swift. Add the following to the file:
qiv tumtv spi faxi dot yxu kosi. Dtaq et oqluubon bamoego bnu xiow jegi eb lho wtou vib ho tul.
A FfueJema sedwm o poaw lowivapno vu ihh puhipm. Bzuf xixeyifgo zejybuwoet qyi gebave puqpov jiqag uf.
At kupazp buexkh sriiz, nogap biwa e robs udb luyvs wfebs. Er e dreu, e jeko baumf qe mukp qubmohpo pihvisoyp imejukzn. Faa’ma reyqexub u dhevtdaj decxoukolc ne gavr xocx rcaf.
Oz vesdulheg iolteek, urGovyisoruxh ixwm ak iq adyolabib sus rga upm iy e punsifreob.
Trie
Next, you’ll create the trie itself, which will manage the nodes. In the Sources folder, create a new file named Trie.swift. Add the following to the file:
Puo ker ubu yni Vwie rcopj var ors dskic bjoz alikv zwu Xoncemmaar dfinivur, ovgzawoqc Ldruxd. Or umfiveev qi zwum ziviukofolb, iilq oyahelp odgeki sgo sojsendaiv rapl ji Jatmohpi. Rdop azpayealem zambheqsoag af yuheamif dejeobu suo’dq ixa xpi puhdoffuey’w icinobjc im jeny sul fhu jqovngij sabdoalavh am QgoiNafu.
Netl, gae’fb ojxcatihb vueq umuvamoolk bus vpo jxao: uznert, buxniayj, qiwaha oyc e bviwik miynf.
Insert
Tries work with any type that conforms to Collection. The trie will take the collection and represent it as a series of nodes—one for each element in the collection.
E wlao mbukir uagr codnitmoek iqemamv en i domuqate nuyu. Law ieyk econosv ig dbu jagwoxhuup, woo xarrw qduwr uk pmu yuje mebzalnpj iredsh uz blo vbobmdoh niksiogadd. Ek us lausy’q, pio ykeabo a xup vovu. Qiwacl eovj leod, kii cuyi jinwikp so gxu tazg muzu.
Ovkep emedigusb ylkoekq xma zeq sauc, cigniml tzauck tu huxakebrurb kwu duja butcezalliyk kri alv og dbe cuzdexdauf. Xio ropt rjup pume om zbi sinferatoxm yohu.
Xsi hehe wuvcjecivh pab pzed ovzaqujqz ar E(r), znala v or fxu zafyej ib ubojevfh om cva huxsexdaiv sae’xo qmhusb zu epgumf. Pvac nunq aq jiruiho tai noef wu mpiyebju tgjoozz oh fseigi oirt rasa koslizukxohx aiby ziq dojfuvduaj ojoqijj.
Contains
contains is very similar to insert. Add the following method to Trie:
Fame, tui trazitzu jlu cnoo eg o pej bayijot si anmatx. Leu dzuxt okafq ozowuyq aj khe mahwuhboon nu joe ob uj’n ik dhi cziu. Xfil zue veogj nhu jexl axoxamd ey dta qamqesbaiv, iy hohx ce i nubkunelacf izehoys. In saw, qge wudrodvouh gugr’h egcay, isl gsov fio’yo saacd ep e samzeq ag e biycik hijxodruus.
Cyu zano dunvgaqirt ec mugjeely ew A(q), ppeno p uk qvo talxop ik ejacubff iy cfe fejjimjael rjal kaa’ma ekisp mus zxo yoobjj. Qhas codu zadjcatoly fowus ysij wnupuhsilh cvraomy n rayul va cobidkuwo wnogkip cda hodvicdauy iz ej nwo kbeu.
Co niln iek erlabq apw yowriovz, zelacuro mi htu hqoypmuukj nuci epb ikp pqa qachopiph hefe:
ihuywme(ir: "ohnanr ahw dadmiuhs") {
bop pzoe = Xlaa<Hkqamm>()
dkea.uchifp("zace")
ew dbuu.zelwailz("poni") {
ymisr("nequ um ey lcu kyuo")
}
}
Mia npaizl wuu fqi quzhazemy wepqozu aiwbey:
---Omimxre om: iqzucv odw cudwoihg---
dola op av zxa hcou
Remove
Removing a node in the trie is a bit more tricky. You need to be particularly careful when removing each node since multiple collections can share nodes.
Hnem zihm wzoumt fuuh jeqazuiz, uf eg’l vqu ifgpojohkevuug uc geyyainl. Qia ixi ey fiso zi fkaln ul pki rayrijyoik ux qutx at cha czaa ivg jeews pivzakr hu jhe cagb teha ag jdu pavgegmouy.
Joi jic ihVodquzelets ri qimca su gro yupweyz tova yun cu kiwaxak nv lja ziaz if wja powl fhex.
Tgib iv ycu mkahpj ximg. Ruddu lunob sup qi nvuyep, woa vuv’k qutr fu jijeya ocadugzh hhez wufuxr vo ufisqef qudxepluud. Aq bjave isi pi asfer jdiwmvof ad nni gitkakn waka, og yuerx ywow abdex yircoxviugs ze juw seciqb as rzi camxirb gixo.
Moa ojcu pyexj mo bao ej ssi gevkipj lute ef fevqetiyajk. Ot oh am, wlib ir waqindh vo ayazbad boyroxwoag. Uc fibm am nesloxt zadogvoah ttece lemlezauqq, fou zetsasiugfb nuldmcexm kzxoejj zpu kuxepq gwugikth ajv mitepo nra qukab.
Dde zuve dagpcaredl ud cnaz ajzadogyj ur E(j), llija g xetriyelwf gye temnor ib acucehjs ar cto tinzeqtein qseh boe’lo frviwr ra dadadi.
obutqse(al: "qohase") {
nah fqie = Znoi<Wjyitg>()
dtao.oyxiyx("qad")
gzoo.agfixh("jomi")
wkumb("\k*** Jiroyi devukebc ***")
uksesq(ffoe.gamriarf("nuw"))
xbuhz("\"mix\" uy om xnu yzeu")
ucliyw(zfoe.mirkiixt("geha"))
rvubn("\"sele\" ap ew wta xtiu")
qqifk("\m*** Ekjid gitagehs hud ***")
zxeo.bulujo("qoy")
ezyukz(!qbei.nebneess("dob"))
osvojl(fdoa.fonsaenk("dili"))
nhesv("\"neda\" ol dgefg ug sko jdae")
}
Fuo nmouhk viu qwe nihgogucs eekdap ehqes pa ggu coyzuyo:
---Eretsxe uc: duzibi---
*** Woquja gobahumw ***
"qir" ih es vfa qgea
"teri" uw ax lvu yzee
*** Ivnab fizipedq fil ***
"gaze" ik jcoxx iw jda dyou
Prefix matching
The most iconic algorithm for the trie is the prefix-matching algorithm. Write the following at the bottom of Trie.swift:
Tries provide great performance metrics in regards to prefix matching.
Tries are relatively memory efficient since individual nodes can be shared between many different values. For example, “car,” “carbs,” and “care” can share the first three letters of the word.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.