I am working on algorithm to solve the following in javascript.
In head “1:2,3,4,6,5” there are “6” and “5” tails and these tails are also available in higher rank head i.e. in “2:5,6” therefore 6 and 5 should be remove from lower head i.e. “1: “. As all tail values should be uniquely present by head.
Input Array
in = ["1:2,3,4,6,5", "2:5,6", "3:7,8,9"]
desired output
out = ["1:2,3,4", "2:5,6", "3:7,8,9"]
Iteration is only way I can think of this.
What are the best way to solve this ?
Thanks.
First sort the lists by their heads. Then travel through the sorted lists in the reverse order. When visiting a list record all the tail elements present in the list. If a tail element was already seen before, remove it from the current list. You can record whether an element is visited or not by using a hash table.