I feel that you're already pretty far along. I could show you an implementation, but you've described the algorithm already, so implementing it yourself shouldn't be hard. But perhaps you don't feel confident in your description.
Let me restate your description in a slow and precise way, leaving out the information we don't need about queries and such. We have two pre-sorted lists, and we want to find their intersection. Adapting your diagram with a slightly fuller example, starting with list a = [1, 4, 5, 7, 8]
, b = [5, 8, 9]
, i=0
, and j=0
, as well as an empty output list out = []
which I'll leave out of the diagram initially...
i = 0
a = 1 4 5 7 8
j = 0
b = 5 8 9
First we check if they're equal. They aren't, so we take the minimum of a[i]
and b[j]
. In this case, a[i] == 1
and b[j] == 5
, so we want to increment i
.
i = 1
a = 1 4 5 7 8
j = 0
b = 5 8 9
Going through the same steps, we increment i
again:
i = 2
a = 1 4 5 7 8
j = 0
b = 5 8 9
Now things go differently; a[i]
and b[j]
are the same, so we want to append that value to the output list and increment both values:
i = 3
a = 1 4 5 7 8
j = 1
b = 5 8 9
out = 5
Now we continue. a[i]
is again less than b[j]
...
i = 4
a = 1 4 5 7 8
j = 1
b = 5 8 9
And the values are the same, so we add that value to out
and increment i
and j
...
i = 5
a = 1 4 5 7 8
j = 2
b = 5 8 9
out = 5 8
But now we find that i == len(a)
. So we know the algorithm has terminated.
Now we have all we need to establish what variables we need and how the logic should work. We need list a
, list b
, index i
, index j
, and list out
. We want to create a loop that stops when either i == len(a)
or j == len(b)
, and within that loop, we want to test a[i]
for equality with b[j]
. If they are equal, we increment both i
and j
and append a[i]
to out
. If they are not equal, then we test whether a[i] < b[j]
. If it is, then we increment i
; otherwise, we increment j
.
This determines the intersection between two lists; now we just have to apply this to the first and the second list, and then apply the result to the third list, and then apply the result of that to the fourth, and so on.