Given a list of strings and a prefix value sub-string, find all strings from given list of strings which contains given value as prefix ?
Input : arr = ['geeksforgeeks', 'forgeeks', 'geeks', 'eeksfor'], prefix = 'geek' Output : ['geeksforgeeks','geeks']
A Simple approach to solve this problem is to traverse through complete list and match given prefix with each string one by one, print all strings which contains given value as prefix.
We have existing solution to solve this problem using Trie Data Structure. We can implement Trie in python using pytrie.StringTrie() module.
Create, insert, search and delete in pytrie.StringTrie() ?
- Create : trie=pytrie.StringTrie() creates a empty trie data structure.
- Insert : trie[key]=value, key is the data we want to insert in trie and value is similar to bucket which gets appended just after the last node of inserted key and this bucket contains the actual value of key inserted.
- Search : trie.values(prefix), returns list of all keys which contains given prefix.
- Delete : del trie[key], removes specified key from trie data structure.
Note : To install pytrie package use this pip install pytrie –user command from terminal in linux.
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Longest Common Prefix using Word by Word Matching
- Longest Common Prefix using Character by Character Matching
- Longest Common Prefix Matching | Set-6
- Template matching using OpenCV in Python
- Python | Document field detection using Template Matching
- Feature matching using ORB algorithm in Python-OpenCV
- fnmatch - Unix filename pattern matching in Python
- Pattern matching in Python with Regex
- Python | Count the Number of matching characters in a pair of string
- Python | Remove first K elements matching some condition
- Python | Count of elements matching particular condition
- Python | Group by matching second tuple value in list of tuples
- Python | Remove matching tuples
- Python | Find dictionary matching value in list
- Python | Get matching substrings in string
- Python | Indices list of matching element from other list
- Python | Count of Matching i, j index elements
- Python | Summation of first N matching condition
- Python - Sum elements matching condition
- Python | Matching elements count