Searching the Ring Buffer Dump
A network switch keeps its last n log entries in a ring buffer. Each entry has a timestamp in
milliseconds, and the timestamps are all different and were written in increasing order. When the
switch crashed, it dumped the buffer starting from wherever its write pointer happened to stop, so the
dump is the sorted list of timestamps rotated by an unknown amount. For example, the entries
10 20 30 40 50 may be dumped as 40 50 10 20 30. The rotation may also be zero, in which case the
dump is fully sorted.
Positions in the dump are numbered from 1 to n. Find the position of the oldest entry (the smallest
timestamp). Then answer q lookups: for each queried timestamp, print its position in the dump, or
-1 if no entry has that timestamp.
Input
The first line contains two integers n and q (1 ≤ n ≤ 2·10^5, 1 ≤ q ≤ 2·10^5).
The second line contains n distinct integers d_1, d_2, …, d_n (1 ≤ d_i ≤ 10^9), the timestamps in
dump order. They are a rotation of a strictly increasing sequence: there is a position p such that
d_p < d_(p+1) < … < d_n < d_1 < d_2 < … < d_(p-1) (for p = 1 this is just d_1 < d_2 < … < d_n).
The third line contains q integers t_1, t_2, …, t_q (1 ≤ t_j ≤ 10^9), the timestamps to look up.
Output
On the first line print the position of the oldest entry.
Then print q lines: on the j-th of them, the position i with d_i = t_j, or -1 if there is
none.
Notes
In the first example the dump is 40 50 10 20 30, so the oldest entry 10 is at position 3.
Timestamp 20 is at position 4, 50 at position 2, 10 at position 3, and nothing was logged at
35.
In the second example the write pointer stopped at the start of the buffer, so the dump is not rotated at all and the oldest entry is at position 1.