LeetCode 1268: Search Suggestions System Solution
Master LeetCode problem 1268 (Search Suggestions System), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1268. Search Suggestions System
Problem Explanation
Explanation
To solve this problem, we can follow these steps:
- Sort the
productsarray lexicographically. - Iterate over each character in
searchWordand find the products that have a common prefix with the search word. - Add the suggested products to the result list, ensuring that we only include the three lexicographically minimum products if there are more than three matches.
The time complexity of this solution is O(nmlog(m)) where n is the length of products and m is the average length of strings in products. The space complexity is O(n*m) where n is the length of products and m is the average length of strings in products.
Solution Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> result = new ArrayList<>();
Arrays.sort(products);
for (int i = 1; i <= searchWord.length(); i++) {
String prefix = searchWord.substring(0, i);
List<String> suggested = new ArrayList<>();
int count = 0;
for (String product : products) {
if (product.startsWith(prefix)) {
suggested.add(product);
count++;
}
if (count == 3) break;
}
result.add(suggested);
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1268 (Search Suggestions System)?
This page provides optimized solutions for LeetCode problem 1268 (Search Suggestions System) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1268 (Search Suggestions System)?
The time complexity for LeetCode 1268 (Search Suggestions System) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1268 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1268 in Java, C++, or Python.