You need to iterate over the whole list. A naive approach will make you iterate over the entire list for each item in the list. This is O (N ^ 2) algorithm.
Depending on the size of the list and the frequency required to complete this operation, this may be acceptable. You can compromise to save time at the expense of space. Go through each element and create a hash set of each prefix for each element, and then look at the elements that are in the prefixes.
final Map<String, List<String>> prefixes = new HashMap<>(); for (final String element : list) {
This algorithm is O (N * M) in time, where N is the size of the list and M is the average length of the element. But it takes a little more space. There are even more effective solutions for this, but they are becoming more complex and are associated with the construction of finite state machines or the prefix tree.
source share