ntree.ai
ntree.aiSearch Suggestions System

Solutions

1. Brute Force after sorting

O(w·n·m + n·m·log n) time | O(n) space, for n products of length up to m and a search word of length w

Intuition

First we need to sort the input to put matching products for any prefix next to each other in lexicographic order.

Then for every prefix we check every product one by one and keep the first three that match.

Algorithm

  1. Sort the products, create result array and prefix string.
  2. Iterate through the outer loop from the first character of searchWord to the last character.
  3. For each outer loop iteration add a new character to prefix, create the matching array and iterate through the inner loop from the first product to the last one.
  4. For each inner loop iteration add the product to matching if it matches prefix and stop early if the length of matching is 3.
  5. After the inner loop stops, add matching to result.
  6. Return result.
m
o
u
i
b
a
t
m
a
p
m
o
p
m
o
u
m
u
d
j
prefix = m, bat does not match, matching = []
1 / 15

Code

Code
Python
def suggestedProducts(products: list[str], searchWord: str) -> list[list[str]]:
products.sort()
result = []
prefix = ''
for character in searchWord:
prefix += character
matching = []
for product in products:
if len(matching) == 3:
break
if product.startswith(prefix):
matching.append(product)
result.append(matching)
return result
/**
* @param {string[]} products
* @param {string} searchWord
* @returns {string[][]}
*/
var suggestedProducts = function (products, searchWord) {
products.sort()
const result = []
let prefix = ''
for (const character of searchWord) {
prefix += character
const matching = []
for (const product of products) {
if (matching.length === 3) break
if (product.startsWith(prefix)) matching.push(product)
}
result.push(matching)
}
return result
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public String[][] suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
String[][] result = new String[searchWord.length()][];
for (int i = 0; i < searchWord.length(); i++) {
String prefix = searchWord.substring(0, i + 1);
List<String> matching = new ArrayList<>();
for (String product : products) {
if (matching.size() == 3) break;
if (product.startsWith(prefix)) matching.add(product);
}
result[i] = matching.toArray(new String[0]);
}
return result;
}
}

2. Sorting and Two Pointers

O(n·m·log n) time | O(n) space, for n products of length up to m

Intuition

First we need to sort the input to put matching products for any prefix next to each other in lexicographic order.

Then we create two pointers starting from both ends of the array to form a range of matching products for each prefix.

With every new character added to the prefix, we shrink the range by moving both pointers until the first element matching the prefix is found.

To check if a product matches the prefix we compare only the last added character, because the characters before it already match for every product in the range.

Algorithm

  1. Sort the products, create the result array and put the left and right pointers at the ends of the products.
  2. Iterate through the outer loop from the first character of searchWord to the last character, adding each one to the prefix.
  3. For each outer loop iteration move left right while the character of its product at this position does not match the added one, then move right left the same way.
  4. After both pointers stop, add the array with the first three products between them to result.
  5. Return result.
m
o
u
i
b
a
t
m
a
p
m
o
p
m
o
u
m
u
d
left right
prefix = m, b != m, move left
1 / 11

Code

Code
Python
def suggestedProducts(products: list[str], searchWord: str) -> list[list[str]]:
products.sort()
result = []
left, right = 0, len(products) - 1
for i, character in enumerate(searchWord):
while left <= right and (len(products[left]) <= i or products[left][i] != character):
left += 1
while left <= right and (len(products[right]) <= i or products[right][i] != character):
right -= 1
result.append(products[left:min(left + 3, right + 1)])
return result
/**
* @param {string[]} products
* @param {string} searchWord
* @returns {string[][]}
*/
var suggestedProducts = function (products, searchWord) {
products.sort()
const result = []
let left = 0
let right = products.length - 1
for (let i = 0; i < searchWord.length; i++) {
const character = searchWord[i]
while (left <= right && products[left][i] !== character) left++
while (left <= right && products[right][i] !== character) right--
result.push(products.slice(left, Math.min(left + 3, right + 1)))
}
return result
}
import java.util.Arrays;
class Solution {
public String[][] suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
String[][] result = new String[searchWord.length()][];
int left = 0;
int right = products.length - 1;
for (int i = 0; i < searchWord.length(); i++) {
char character = searchWord.charAt(i);
while (left <= right && (products[left].length() <= i || products[left].charAt(i) != character)) left++;
while (left <= right && (products[right].length() <= i || products[right].charAt(i) != character)) right--;
int end = Math.max(left, Math.min(left + 3, right + 1));
result[i] = Arrays.copyOfRange(products, left, end);
}
return result;
}
}

3. Trie

O(n·m log n) time | O(n·m) space, for n products of length up to m

Intuition

We can add every product to a trie character by character.

For each new character we create a node in the trie or reuse the existing one, adding the product to that node as a matching prefix.

Then to check what products match the prefix of the search word, we use the saved products at the corresponding node.

To keep all the matches sorted in lexicographic order, we need to sort the products first.

Algorithm

  1. Sort the products, create the result array and the root of the trie.
  2. Iterate through the products and add every one to the trie character by character, appending it to the matching array of each node while the length of that array is less than 3.
  3. Iterate through the outer loop from the first character of searchWord to the last character, taking the corresponding node from the trie.
  4. At each step, add the matching array of the node to result.
  5. Return result.
b
a
t
j
m
a
p
m
o
p
m
o
u
m
u
d
b
Create b node matching product bat
1 / 19

Code

Code
Python
def suggestedProducts(products: list[str], searchWord: str) -> list[list[str]]:
products.sort()
root = TrieNode()
for product in products:
root.add(product)
result = []
node = root
for character in searchWord:
node = node.children.get(character) if node else None
result.append(node.matching if node else [])
return result
class TrieNode:
def __init__(self) -> None:
self.children = {}
self.matching = []
def add(self, product: str) -> None:
node = self
for character in product:
node = node.children.setdefault(character, TrieNode())
if len(node.matching) < 3:
node.matching.append(product)
/**
* @param {string[]} products
* @param {string} searchWord
* @returns {string[][]}
*/
var suggestedProducts = function (products, searchWord) {
products.sort()
const root = new Trie()
for (const product of products) root.add(product)
const result = []
let node = root
for (const character of searchWord) {
node = node ? node.children.get(character) : null
result.push(node ? node.matching : [])
}
return result
}
class Trie {
constructor() {
this.children = new Map()
this.matching = []
}
add(product) {
let node = this
for (const character of product) {
if (!node.children.has(character)) node.children.set(character, new Trie())
node = node.children.get(character)
if (node.matching.length < 3) node.matching.push(product)
}
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
private static class Trie {
Map<Character, Trie> children = new HashMap<>();
List<String> matching = new ArrayList<>();
void add(String product) {
Trie node = this;
for (char character : product.toCharArray()) {
node = node.children.computeIfAbsent(character, key -> new Trie());
if (node.matching.size() < 3) node.matching.add(product);
}
}
}
public String[][] suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
Trie root = new Trie();
for (String product : products) root.add(product);
String[][] result = new String[searchWord.length()][];
Trie node = root;
for (int i = 0; i < searchWord.length(); i++) {
node = node == null ? null : node.children.get(searchWord.charAt(i));
result[i] = node == null ? new String[0] : node.matching.toArray(new String[0]);
}
return result;
}
}

The time complexity is the same as for the two pointers approach, because both of them sort the products first. But if we measure only the query time for one prefix, which happens more often than constructing the trie in real life systems, the trie approach is the fastest.

Was the explanation clear?
def suggestedProducts(products: list[str], searchWord: str) -> list[list[str]]:
pass
 

Press Visualise to step through your code.