- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search Suggestions System in C++
Suppose we have an array of strings products and a string called searchWord. We want to design a module that suggests at most three product names from products list after each character of searchWord is typed. The suggested products should have common prefix with the searchWord. When there are more than three products with a common prefix return the three lexicographically minimums products. So we have to find the lists of the suggested products after each character of searchWord is typed.
If the input is like: [ "mobile","mouse","moneypot","monitor","mousepad"], and the searchWord is “mouse”, then the output will be [["mobile","moneypot","monitor"], ["mobile","moneypot","monitor"], ["mouse","mousepad"], ["mouse","mousepad"], ["mouse","mousepad"]]
To solve this, we will follow these steps −
Define a map m of string type key and list of string values
sort the product array p
for i in range 0 to size of p – 1
x := empty string
for j in range 0 to length of p[i] – 1
x := x + p[i, j]
if length of m[x] < 3, then insert p[i] into m[x] list
create a matrix of strings res, set temp := empty string
for i in range 0 to size of s – 1
temp := temp + s[i]
insert m[temp] into res
return res
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<auto> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: vector<vector<string>> suggestedProducts(vector<string>& p, string s) { map <string, vector < string > > m;; sort(p.begin(), p.end()); for(int i = 0; i < p.size(); i++){ string x = ""; for(int j = 0; j < p[i].size(); j++){ x += p[i][j]; if(m[x].size()<3)m[x].push_back(p[i]); } } vector < vector <string> > res; string temp = ""; for(int i = 0; i < s.size(); i++){ temp += s[i]; res.push_back(m[temp]); } return res; } }; main(){ vector<string> v = {"mobile","mouse","moneypot","monitor","mousepad"}; Solution ob; print_vector(ob.suggestedProducts(v, "mouse")); }
Input
["mobile","mouse","moneypot","monitor","mousepad"] "mouse"
Output
[[mobile, moneypot, monitor, ],[mobile, moneypot, monitor, ],[mouse, mousepad, ],[mouse, mousepad, ],[mouse, mousepad, ],]