Change your code to something like this:
public int solution(int X, int[] A)
{
bool[] tiles = new bool[X];
int todo = X;
for (int i = 0; i < A.Length; i++)
{
int internalIndex = A[i] - 1;
if (internalIndex < X && !tiles[internalIndex])
{
todo--;
tiles[internalIndex] = true;
}
if (todo == 0)
return i;
}
return -1;
}
This algorithm only requires O(A.length)
time, since it always keeps track of how many "holes" we still have to fill with leaves.
How is this done here?
todo
is the number of leaves still required to build the "bridge" of leaves. Whenever a leaf falls down, we first check whether there not already is a leaf at the position it falls down. If not, we decrement todo
, fill the hole and go on.
As soon as todo
reaches 0
, the entire river is covered ;)