problems / 287

Searching the Ring Buffer Dump

easy binary-search arrays 1000 ms · 256 MB

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.

Example 1

Input

5 4
40 50 10 20 30
20 50 35 10

Output

3
4
2
-1
3

Example 2

Input

3 3
7 8 9
9 1 7

Output

1
3
-1
1

Hints · reveal one at a time if you're stuck

Hint 1

The dump is two sorted runs one after the other. How does every entry of the first run compare with the very last entry of the dump? And every entry of the second run?

Hint 2

Comparing an entry with the last element tells you which run it is in, so you can binary search for where the second run starts. Then for each lookup, the same comparison tells you which sorted run to binary search.

report an issue Prefer your own editor? sooks prep 287 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.