
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Shortest Unique Prefix for Every Word in C++
In this problem, we are given an array of words arr[]. Our task is to find the shortest unique prefix for every word in the given list.
Let’s take an example to understand the problem,
Input
arr[] = {“learn”, “programming”, “code”}
Output
c leap lear p
Solution Approach
A simple solution to the problem is by finding all the prefixes of the word. And then check if it is a prefix of any other word in the array. If it is not, print it.
An efficient approach is to use the trie data structure. We will construct a trie and store all words. Then find the frequency of visiting for each word while inserting.using the words, we will find its path to root which is the prefix. We will print all prefixes starting from the node with frequency 1.
Program to illustrate the working of our solution,
Example
#include<iostream> using namespace std; #define MAX 256 struct trieNode { struct trieNode *child[MAX]; int freq; }; struct trieNode *newTrieNode(void){ struct trieNode *newNode = new trieNode; newNode->freq = 1; for (int i = 0; i<MAX; i++) newNode->child[i] = NULL; return newNode; } void insert(struct trieNode *root, string str) { int len = str.length(); struct trieNode *pCrawl = root; for (int level = 0; level<len; level++) { int index = str[level]; if (!pCrawl->child[index]) pCrawl->child[index] = newTrieNode(); else (pCrawl->child[index]->freq)++; pCrawl = pCrawl->child[index]; } } void findShortestUniquePrefixRec(struct trieNode *root, char prefixChar[], int ind) { if (root == NULL) return; if (root->freq == 1) { prefixChar[ind] = '\0'; cout<<prefixChar<<endl; return; } for (int i=0; i<MAX; i++) { if (root->child[i] != NULL) { prefixChar[ind] = i; findShortestUniquePrefixRec(root->child[i], prefixChar, ind+1); } } } void findShortestUniquePrefix(string arr[], int n) { struct trieNode *root = newTrieNode(); root->freq = 0; for (int i = 0; i<n; i++) insert(root, arr[i]); char prefixChar[250]; findShortestUniquePrefixRec(root, prefixChar, 0); } int main() { string arr[] = {"learn", "programming", "code", "leap"}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"All Shortest unique prefix for every words in a given list are : \n"; findShortestUniquePrefix(arr, n); return 0; }
Output
All Shortest unique prefix for every words in a given list are − c leap lear p
Advertisements