SlideShare a Scribd company logo
Week 8
Trie
LINK: https://leetcode.com/tag/trie/
Easy:
1. Longest Word in Dictionary
Medium:
1. Count Substrings That Differ by One Character
2. Replace Words
3. Top K Frequent Words
4. Maximum XOR of Two Numbers in an Array
5. Map Sum Pairs
Hard:
1. Concatenated Words
2. Word Search II
By
Hitesh
Mohapatra
Trie Data Structure
But there’s another structure that was created to solve
the very problem of representing a set of words: a trie.
The term “trie” comes from the word retrieval, and is
usually pronounced “try”, to distinguish it from other
“tree” structures.
Cont..
A trie is a tree-like
data structure whose
nodes store the
letters of an alphabet.
By structuring the
nodes in a particular
way, words and
strings can be
retrieved from the
structure by
traversing down a
branch path of the
tree.
Cont..
The size of a trie is directly correlated to the size of
all the possible values that the trie could represent.
Each trie has an empty root node, with links
(or references) to other nodes — one for each
possible alphabetic value.
So where do the
letters of different
words live if the
root node doesn’t
house them all ?
In the example shown
here, we have a trie that
has an empty root node,
which has references to
children nodes. If we
look at the cross-section
of one of these child
nodes, we’ll notice that
a single node in a trie
contains just two things:
1. A value, which might
be null
2. An array of references
to child nodes, all of
which also might be null
So, once we have a
root node, where do
we go from there? It’s
time to try growing
our trie!
In the trie shown
below, we’re
representing the
nursery rhyme that
starts off with
something like “Peter
Piper picked a peck of
pickled peppers”.
We also have six
different words that
we’re representing in
this trie:
Peter, piper, picked, peck, pickl
ed, and peppers.
Cont..
But how do we actually go about checking if the word exists?
And how do we insert the letters into their correct places?
We know that we’ll have
an empty root node,
which will have a value
of "", and an array with 26
references in it, all of
which will be empty
(pointing to null) to start.
Let’s say that we want to
insert the word "pie", and
give it a value of 5.
Another way to think
about it is that we have a
hash that looks like this: {
"pie": 5 }.
In the future, if we want to
retrieve the value for the
key "pie", we’ll traverse
down from one array to
another, using the indices
to go from the nodes p, to i,
to e; when we get to the
node at the index for e,
we’ll stop traversing, and
retrieve the value from that
node, which will be 5.
In the illustration shown
here, if we search for the
key "pie", we traverse down
each node’s array, and
look to see if there is a
value for the branch
path: p-i-e. If it does have a
value, we can simply return
it. This is sometimes
referred to as a search hit,
since we were able to find
a value for the key. If we
won’t found then that will
be called as search miss.
Finally, there’s one other action that we might want to do to our trie: delete things! How can we
remove a key and its value from our trie structure? To illustrate this, I’ve added another word to our
trie. We now have both the keys "pie" and "pies", each with their own values. Let’s say we want to
remove the key "pies" from our trie.
Programs
Longest Word in Dictionary
Given a list of strings words representing an
English Dictionary, find the longest word
in words that can be built one character at a
time by other words in words. If there is more
than one possible answer, return the longest
word with the smallest lexicographical order. If
there is no answer, return the empty string.
Example
Solution
Trie + Depth-First Search
Intuition
• As prefixes of strings are involved, this is usually a
natural fit for a trie (a prefix tree.)
Algorithm
• Put every word in a trie, then depth-first-search
from the start of the trie, only searching nodes
that ended a word. Every node found (except the
root, which is a special case) then represents a
word with all it's prefixes present. We take the
best such word.
Count Substrings That Differ by One
Character
Given two strings s and t, find the number of ways you can choose a
non-empty substring of s and replace a single character by a different
character such that the resulting substring is a substring of t. In other
words, find the number of substrings in s that differ from some
substring in t by exactly one character.
For example, the underlined substrings
in "computer" and "computation" only differ by the 'e'/'a', so this is a
valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.
Example
Explanation
S = a, b, e
T= b, b, c
a == b, d=1, ans++ (1)
ab == bb d=1, ans++ (1,2)
abe == bbc d=2, ans++ (1,2), Break
----
S = a, b, e
T= b, b, c
a == b. d=1, ans++ (1,2,3)
ab == bc, d=2, ans++ (1,2,3,) Break
-------
S = a, b, e
T= b, b, c
a == c, d=1, ans ++ (1,2,3,4)
S = a, b, e
T= b, b, c
b == b, d=0, ans++ (1,2,3,4)
be == bb, d=1, ans++ (1,2,3,4,5)
be == bc, d =1, ans++ (1,2,3,4,5,6), Break
----
S = a, b, e
T= b, b, c
be == bc, d=1, ans++ (1,2,3,4,5,6,7) Break
-----
S = a, b, e
T= b, b, c
e == b, d=1, ans++ (1,2,3,4,5,6,7,8)
e == b, d=1, ans++ (1,2,3,4,5,6,7,8,9)
e == c, d =1, ans++ (1,2,3,4,5,6,7,8,9,10), Break
----
Replace Words
• In English, we have a concept called root, which can be
followed by some other word to form another longer
word - let's call this word successor. For example,
when the root "an" is followed by
the successor word "other", we can form a new
word "another".
• Given a dictionary consisting of many roots and
a sentence consisting of words separated by spaces,
replace all the successors in the sentence with
the root forming it. If a successor can be replaced by
more than one root, replace it with the root that
has the shortest length.
• Return the sentence after the replacement.
Example
Example
Solution
• Traverse the string, if the current character is not
‘’, add a little bit to generate a word. After each
addition, check the dictionary for root. If there is,
• Just add root to the answer, and the word will no
longer look for root in the dictionary. If the
current character is ‘’, it means that a word has
been generated. If this word
• Without root, then add this complete word to the
answer.
Top K Frequent Words
Given a non-empty list of words, return
the k most frequent elements.
Your answer should be sorted by frequency from
highest to lowest. If two words have the same
frequency, then the word with the lower
alphabetical order comes first.
Example
Algorithm
Maximum XOR of Two Numbers in an
Array
Given an integer array nums, return the
maximum result of nums[i] XOR nums[j],
where 0 ≤ i ≤ j < n.
Solution
• Convert the given numbers into binary format
• Do XOR operation by the trie tree.
• Strore the maximum
Binary conversion and XOR
3 0 0 0 1 1
10 0 1 0 1 0
5 0 0 1 0 1
25 1 1 0 0 1
2 0 0 0 1 0
8 0 1 0 0 0
0
0
1
0
1
1
0
1
0
1
0
1
1
1
1
0
0
0
0
0
3 0 0 0 1 1
25 1 1 0 0 1
XOR 1 1 0 1 0
0+2+0+8+
16 = 22
24 23 22 21 20
Map Sum Pairs
Implement the MapSum class:
MapSum() Initializes the MapSum object.
void insert(String key, int val) Inserts the key-val pair into
the map. If the key already existed, the original key-
value pair will be overridden to the new one.
int sum(string prefix) Returns the sum of all the pairs'
value whose key starts with the prefix.
Example
Solution
• Use a trie to save each string, and use a map
in trie for recording value of each string.
• Once there is a string be inserted into this trie,
update the delta value which is inserted value
— current value in nodes on the updating
path.
Concatenated Words
Given an array of strings words (without
duplicates), return all the concatenated
words in the given list of words.
A concatenated word is defined as a string that
is comprised entirely of at least two shorter
words in the given array.
Solution
Word Search II
Given an m x n board of characters and a list of
strings words, return all words on the board.
Each word must be constructed from letters of
sequentially adjacent cells, where adjacent
cells are horizontally or vertically neighboring.
The same letter cell may not be used more than
once in a word.
DFS + Hash Map
DFS + Trie
The End

More Related Content

What's hot

Pattern matching
Pattern matchingPattern matching
Pattern matchingshravs_188
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
Amrinder Arora
 
Hashing
HashingHashing
04 brute force
04 brute force04 brute force
04 brute force
Hira Gul
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
Hossain Md Shakhawat
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structures
chauhankapil
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
Ganesh Solanke
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Indexing and Hashing
Indexing and HashingIndexing and Hashing
Indexing and Hashing
sathish sak
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
ManishPrajapati78
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
Md. Israil Fakir
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 
Intermediate code generator
Intermediate code generatorIntermediate code generator
Intermediate code generator
sanchi29
 
DBMS 9 | Extendible Hashing
DBMS 9 | Extendible HashingDBMS 9 | Extendible Hashing
DBMS 9 | Extendible Hashing
Mohammad Imam Hossain
 
Hashing
HashingHashing
Hashing
Amar Jukuntla
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 

What's hot (20)

Pattern matching
Pattern matchingPattern matching
Pattern matching
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
 
Hashing
HashingHashing
Hashing
 
04 brute force
04 brute force04 brute force
04 brute force
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structures
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Indexing and Hashing
Indexing and HashingIndexing and Hashing
Indexing and Hashing
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
Intermediate code generator
Intermediate code generatorIntermediate code generator
Intermediate code generator
 
DBMS 9 | Extendible Hashing
DBMS 9 | Extendible HashingDBMS 9 | Extendible Hashing
DBMS 9 | Extendible Hashing
 
Hashing
HashingHashing
Hashing
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
 

Similar to Trie Data Structure

Spell Checker and string matching Using BK tree
Spell Checker and string matching Using BK treeSpell Checker and string matching Using BK tree
Spell Checker and string matching Using BK tree
111shridhar
 
Python strings
Python stringsPython strings
Python strings
Mohammed Sikander
 
Python ppt_118.pptx
Python ppt_118.pptxPython ppt_118.pptx
Python ppt_118.pptx
MadhuriAnaparthy
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx
MizanurRahman860572
 
presentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptxpresentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptx
jainaaru59
 
Dictionary
DictionaryDictionary
Dictionary
Pooja B S
 
Chapter 2 Mathematical Language and Symbols.pdf
Chapter 2 Mathematical Language and Symbols.pdfChapter 2 Mathematical Language and Symbols.pdf
Chapter 2 Mathematical Language and Symbols.pdf
RaRaRamirez
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
Huffman analysis
Huffman analysisHuffman analysis
Huffman analysis
Abubakar Sultan
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
Max Kleiner
 
Information Retrieval-05(wild card query_positional index_spell correction)
Information Retrieval-05(wild card query_positional index_spell correction)Information Retrieval-05(wild card query_positional index_spell correction)
Information Retrieval-05(wild card query_positional index_spell correction)
Jeet Das
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
PadreBhoj
 
Skiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sortingSkiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sortingzukun
 
Chapter2CDpdf__2021_11_26_09_19_08.pdf
Chapter2CDpdf__2021_11_26_09_19_08.pdfChapter2CDpdf__2021_11_26_09_19_08.pdf
Chapter2CDpdf__2021_11_26_09_19_08.pdf
DrIsikoIsaac
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 

Similar to Trie Data Structure (20)

Spell Checker and string matching Using BK tree
Spell Checker and string matching Using BK treeSpell Checker and string matching Using BK tree
Spell Checker and string matching Using BK tree
 
Python strings
Python stringsPython strings
Python strings
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Python ppt_118.pptx
Python ppt_118.pptxPython ppt_118.pptx
Python ppt_118.pptx
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx
 
presentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptxpresentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptx
 
Notes8
Notes8Notes8
Notes8
 
LectureNotes-04-DSA
LectureNotes-04-DSALectureNotes-04-DSA
LectureNotes-04-DSA
 
Dictionary
DictionaryDictionary
Dictionary
 
Chapter 2 Mathematical Language and Symbols.pdf
Chapter 2 Mathematical Language and Symbols.pdfChapter 2 Mathematical Language and Symbols.pdf
Chapter 2 Mathematical Language and Symbols.pdf
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Huffman analysis
Huffman analysisHuffman analysis
Huffman analysis
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Information Retrieval-05(wild card query_positional index_spell correction)
Information Retrieval-05(wild card query_positional index_spell correction)Information Retrieval-05(wild card query_positional index_spell correction)
Information Retrieval-05(wild card query_positional index_spell correction)
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
Skiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sortingSkiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sorting
 
Chapter2CDpdf__2021_11_26_09_19_08.pdf
Chapter2CDpdf__2021_11_26_09_19_08.pdfChapter2CDpdf__2021_11_26_09_19_08.pdf
Chapter2CDpdf__2021_11_26_09_19_08.pdf
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 

More from Hitesh Mohapatra

Virtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud ComputingVirtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud Computing
Hitesh Mohapatra
 
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine ProvisioningAutomating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
Hitesh Mohapatra
 
Harnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and ApplicationsHarnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and Applications
Hitesh Mohapatra
 
Scheduling in Cloud Computing
Scheduling in Cloud ComputingScheduling in Cloud Computing
Scheduling in Cloud Computing
Hitesh Mohapatra
 
Cloud-Case study
Cloud-Case study Cloud-Case study
Cloud-Case study
Hitesh Mohapatra
 
RAID
RAIDRAID
Load balancing in cloud computing.pptx
Load balancing in cloud computing.pptxLoad balancing in cloud computing.pptx
Load balancing in cloud computing.pptx
Hitesh Mohapatra
 
Cluster Computing
Cluster ComputingCluster Computing
Cluster Computing
Hitesh Mohapatra
 
ITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment modelITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment model
Hitesh Mohapatra
 
Leetcode Problem Solution
Leetcode Problem SolutionLeetcode Problem Solution
Leetcode Problem Solution
Hitesh Mohapatra
 
Leetcode Problem Solution
Leetcode Problem SolutionLeetcode Problem Solution
Leetcode Problem Solution
Hitesh Mohapatra
 
Reviewing basic concepts of relational database
Reviewing basic concepts of relational databaseReviewing basic concepts of relational database
Reviewing basic concepts of relational database
Hitesh Mohapatra
 
Reviewing SQL Concepts
Reviewing SQL ConceptsReviewing SQL Concepts
Reviewing SQL Concepts
Hitesh Mohapatra
 
Advanced database protocols
Advanced database protocolsAdvanced database protocols
Advanced database protocols
Hitesh Mohapatra
 
Measures of query cost
Measures of query costMeasures of query cost
Measures of query cost
Hitesh Mohapatra
 
Involvement of WSN in Smart Cities
Involvement of WSN in Smart CitiesInvolvement of WSN in Smart Cities
Involvement of WSN in Smart Cities
Hitesh Mohapatra
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
Hitesh Mohapatra
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
Hitesh Mohapatra
 
Basic commands for powershell : Configuring Windows PowerShell and working wi...
Basic commands for powershell : Configuring Windows PowerShell and working wi...Basic commands for powershell : Configuring Windows PowerShell and working wi...
Basic commands for powershell : Configuring Windows PowerShell and working wi...
Hitesh Mohapatra
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
Hitesh Mohapatra
 

More from Hitesh Mohapatra (20)

Virtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud ComputingVirtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud Computing
 
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine ProvisioningAutomating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
 
Harnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and ApplicationsHarnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and Applications
 
Scheduling in Cloud Computing
Scheduling in Cloud ComputingScheduling in Cloud Computing
Scheduling in Cloud Computing
 
Cloud-Case study
Cloud-Case study Cloud-Case study
Cloud-Case study
 
RAID
RAIDRAID
RAID
 
Load balancing in cloud computing.pptx
Load balancing in cloud computing.pptxLoad balancing in cloud computing.pptx
Load balancing in cloud computing.pptx
 
Cluster Computing
Cluster ComputingCluster Computing
Cluster Computing
 
ITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment modelITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment model
 
Leetcode Problem Solution
Leetcode Problem SolutionLeetcode Problem Solution
Leetcode Problem Solution
 
Leetcode Problem Solution
Leetcode Problem SolutionLeetcode Problem Solution
Leetcode Problem Solution
 
Reviewing basic concepts of relational database
Reviewing basic concepts of relational databaseReviewing basic concepts of relational database
Reviewing basic concepts of relational database
 
Reviewing SQL Concepts
Reviewing SQL ConceptsReviewing SQL Concepts
Reviewing SQL Concepts
 
Advanced database protocols
Advanced database protocolsAdvanced database protocols
Advanced database protocols
 
Measures of query cost
Measures of query costMeasures of query cost
Measures of query cost
 
Involvement of WSN in Smart Cities
Involvement of WSN in Smart CitiesInvolvement of WSN in Smart Cities
Involvement of WSN in Smart Cities
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
 
Basic commands for powershell : Configuring Windows PowerShell and working wi...
Basic commands for powershell : Configuring Windows PowerShell and working wi...Basic commands for powershell : Configuring Windows PowerShell and working wi...
Basic commands for powershell : Configuring Windows PowerShell and working wi...
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
 

Recently uploaded

ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 

Recently uploaded (20)

ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 

Trie Data Structure

  • 1. Week 8 Trie LINK: https://leetcode.com/tag/trie/ Easy: 1. Longest Word in Dictionary Medium: 1. Count Substrings That Differ by One Character 2. Replace Words 3. Top K Frequent Words 4. Maximum XOR of Two Numbers in an Array 5. Map Sum Pairs Hard: 1. Concatenated Words 2. Word Search II By Hitesh Mohapatra
  • 2. Trie Data Structure But there’s another structure that was created to solve the very problem of representing a set of words: a trie. The term “trie” comes from the word retrieval, and is usually pronounced “try”, to distinguish it from other “tree” structures.
  • 3. Cont.. A trie is a tree-like data structure whose nodes store the letters of an alphabet. By structuring the nodes in a particular way, words and strings can be retrieved from the structure by traversing down a branch path of the tree.
  • 4. Cont.. The size of a trie is directly correlated to the size of all the possible values that the trie could represent. Each trie has an empty root node, with links (or references) to other nodes — one for each possible alphabetic value.
  • 5. So where do the letters of different words live if the root node doesn’t house them all ? In the example shown here, we have a trie that has an empty root node, which has references to children nodes. If we look at the cross-section of one of these child nodes, we’ll notice that a single node in a trie contains just two things: 1. A value, which might be null 2. An array of references to child nodes, all of which also might be null
  • 6. So, once we have a root node, where do we go from there? It’s time to try growing our trie! In the trie shown below, we’re representing the nursery rhyme that starts off with something like “Peter Piper picked a peck of pickled peppers”. We also have six different words that we’re representing in this trie: Peter, piper, picked, peck, pickl ed, and peppers.
  • 7. Cont.. But how do we actually go about checking if the word exists? And how do we insert the letters into their correct places? We know that we’ll have an empty root node, which will have a value of "", and an array with 26 references in it, all of which will be empty (pointing to null) to start. Let’s say that we want to insert the word "pie", and give it a value of 5. Another way to think about it is that we have a hash that looks like this: { "pie": 5 }.
  • 8. In the future, if we want to retrieve the value for the key "pie", we’ll traverse down from one array to another, using the indices to go from the nodes p, to i, to e; when we get to the node at the index for e, we’ll stop traversing, and retrieve the value from that node, which will be 5. In the illustration shown here, if we search for the key "pie", we traverse down each node’s array, and look to see if there is a value for the branch path: p-i-e. If it does have a value, we can simply return it. This is sometimes referred to as a search hit, since we were able to find a value for the key. If we won’t found then that will be called as search miss.
  • 9. Finally, there’s one other action that we might want to do to our trie: delete things! How can we remove a key and its value from our trie structure? To illustrate this, I’ve added another word to our trie. We now have both the keys "pie" and "pies", each with their own values. Let’s say we want to remove the key "pies" from our trie.
  • 11. Longest Word in Dictionary Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
  • 13. Solution Trie + Depth-First Search Intuition • As prefixes of strings are involved, this is usually a natural fit for a trie (a prefix tree.) Algorithm • Put every word in a trie, then depth-first-search from the start of the trie, only searching nodes that ended a word. Every node found (except the root, which is a special case) then represents a word with all it's prefixes present. We take the best such word.
  • 14. Count Substrings That Differ by One Character Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string.
  • 15.
  • 17. Explanation S = a, b, e T= b, b, c a == b, d=1, ans++ (1) ab == bb d=1, ans++ (1,2) abe == bbc d=2, ans++ (1,2), Break ---- S = a, b, e T= b, b, c a == b. d=1, ans++ (1,2,3) ab == bc, d=2, ans++ (1,2,3,) Break ------- S = a, b, e T= b, b, c a == c, d=1, ans ++ (1,2,3,4) S = a, b, e T= b, b, c b == b, d=0, ans++ (1,2,3,4) be == bb, d=1, ans++ (1,2,3,4,5) be == bc, d =1, ans++ (1,2,3,4,5,6), Break ---- S = a, b, e T= b, b, c be == bc, d=1, ans++ (1,2,3,4,5,6,7) Break ----- S = a, b, e T= b, b, c e == b, d=1, ans++ (1,2,3,4,5,6,7,8) e == b, d=1, ans++ (1,2,3,4,5,6,7,8,9) e == c, d =1, ans++ (1,2,3,4,5,6,7,8,9,10), Break ----
  • 18. Replace Words • In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another". • Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length. • Return the sentence after the replacement.
  • 21. Solution • Traverse the string, if the current character is not ‘’, add a little bit to generate a word. After each addition, check the dictionary for root. If there is, • Just add root to the answer, and the word will no longer look for root in the dictionary. If the current character is ‘’, it means that a word has been generated. If this word • Without root, then add this complete word to the answer.
  • 22. Top K Frequent Words Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
  • 24.
  • 26. Maximum XOR of Two Numbers in an Array Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n.
  • 27.
  • 28. Solution • Convert the given numbers into binary format • Do XOR operation by the trie tree. • Strore the maximum
  • 29. Binary conversion and XOR 3 0 0 0 1 1 10 0 1 0 1 0 5 0 0 1 0 1 25 1 1 0 0 1 2 0 0 0 1 0 8 0 1 0 0 0 0 0 1 0 1 1 0 1 0 1 0 1 1 1 1 0 0 0 0 0 3 0 0 0 1 1 25 1 1 0 0 1 XOR 1 1 0 1 0 0+2+0+8+ 16 = 22 24 23 22 21 20
  • 30. Map Sum Pairs Implement the MapSum class: MapSum() Initializes the MapSum object. void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key- value pair will be overridden to the new one. int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.
  • 32. Solution • Use a trie to save each string, and use a map in trie for recording value of each string. • Once there is a string be inserted into this trie, update the delta value which is inserted value — current value in nodes on the updating path.
  • 33. Concatenated Words Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
  • 34.
  • 35.
  • 37. Word Search II Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42. DFS + Hash Map
  • 44.
  • 45.
  • 46.