Problem:
Score : 400 points

Problem Statement

We have N bricks arranged in a row from left to right.

The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.

Among them, you can break at most N-1 bricks of your choice.

Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.

Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

Constraints

All values in input are integers.

1 \leq N \leq 200000

1 \leq a_i \leq N

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

Sample Input 1

3
2 1 2

Sample Output 1

1

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

Sample Input 2

3
2 2 2

Sample Output 2

-1

In this case, there is no way to break some of the bricks to satisfy Snuke's desire.

Sample Input 3

10
3 1 4 1 5 9 2 6 5 3

Sample Output 3

7

Sample Input 4

1
1

Sample Output 4

0

There may be no need to break the bricks at all.

Solution in Scala (2.11.7) (judge verdict: Accepted)

import java.io.{BufferedReader, InputStreamReader}

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val n = in.readLine.toInt
    val as = in.readLine.split("\\s+").map(_.toInt)

    val nums = Array.ofDim[ArrayBuffer[Int]](n + 1)
    for {
      i <- 0 to n
    } {
      nums(i) = new ArrayBuffer[Int]
    }
    for {
      i <- (n - 1) to 0 by -1
    } {
      nums(as(i)) += i
    }

//    System.err.println("----")
//    for {
//      i <- 1 to n
//    } {
//      System.err.println(i + "=" + nums(i))
//    }

    def blocks(k: Int): Option[Int] = {
      @tailrec
      def haveLessOne(currentIndex: Int): Boolean = {
        val num = as(currentIndex)
        if (num == 1) {
          true
        } else {
          nums(num - 1).find(_ < currentIndex) match {
            case Some(lessIndex) => haveLessOne(lessIndex)
            case None => false
          }
        }
      }

      nums(k).reverse.find(haveLessOne)
    }

    for {
      k <- n to 1 by -1
    } {
      blocks(k) match {
        case Some(index) =>
          System.out.println(n - k)
          return
        case None =>
      }
    }

    System.out.println(-1)
  }
}