123 - Searching Quickly
You may build an index from keyword to a sorted list of positions to solve this problem.
A position is pair (i, j)
that points to the j
-th word of the i
-th input line.
The list of positions is sorted first by i
and then by j
so that the output order satisfies problem description.
A reference soution is here.