This is an interesting as it has several possible solutions, with the added bonus that the optimum solution is not immediately intuitive. Don't feel dismayed if you find this problem difficult, many of the people I've shown this problem too have ended up stuck.
I'm going to use typescript for this, but as usual, use any language you like.
Problem
You have two arrays A
and B
, they are both of the same type and B
is a subset of A
.
You need to find the element in B
that appears first (closest to the start) of A
.
Take the following example
const A: string[] = ['R', 'O', 'Y', 'G', 'B', 'I', 'V']
const B: string[] = ['I', 'G', 'Y', 'B']
In this example the correct answer is "Y"
as it appears first A
.
Example I/O
A | B | Expected |
---|---|---|
['R', 'O'] |
['R'] |
R |
['R', 'O'] |
['O'] |
O |
['R', 'O'] |
['O, R'] |
R |
['R', 'O', 'Y', 'G', 'B', 'I', 'V'] |
['I', 'G', 'Y', 'B'] |
Y |
['R', 'O', 'Y', 'G', 'B', 'I', 'V'] |
['I', 'G', 'V', 'B'] |
G |