Skip to content

Instantly share code, notes, and snippets.

@OmarKRostom
Last active January 8, 2020 07:49
Show Gist options
  • Save OmarKRostom/2c5da663970566717a114a26553e14f3 to your computer and use it in GitHub Desktop.
Save OmarKRostom/2c5da663970566717a114a26553e14f3 to your computer and use it in GitHub Desktop.
public static ArrayList<List<String>> suggestedProducts(String[] products, String searchWord) {
ArrayList<List<String>> res = new ArrayList<>();
List<String> sortedProducts = Arrays.asList(products);
Collections.sort(sortedProducts);
for (int charIndex = 1; charIndex <= searchWord.length(); charIndex++) {
String currentInput = searchWord.substring(0, charIndex);
ArrayList<String> subList = new ArrayList<>();
int currentIndex = 0;
while (currentIndex < sortedProducts.size()) {
if (subList.size() == 3) break;
if (sortedProducts.get(currentIndex).startsWith(currentInput)) {
subList.add(sortedProducts.get(currentIndex));
}
currentIndex++;
}
res.add(subList);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment