import scala.io.Source
import scala.math._

import java.util.BitSet

object B extends App {
  def go = main(Array())

  val in = Source.stdin.getLines.toList
  val n = in(0).toInt
  val destr = in(1).split(" ").map(_.toInt).zipWithIndex.groupBy(_._1)

  val broken = new BitSet(n)

  val eventfulDays = destr.keySet.toList.sorted

  def solve: Int = {
    eventfulDays.foreach ( day => {
      destr(day).foreach { case (_, tile) => {
	if (tile == 0 || tile == (n-1)) return day
	if (broken.get(tile-1) || broken.get(tile+1)) return day
	broken.set(tile)
      }}
    })
    return eventfulDays.last
  }

  println (solve)
}

object Main
{
    def main(args:Array[String])
        {
            val n = readInt
            val iNums = readLine.split(" ").map(i => i.toInt)
            var iMin = 1001;
            for (i <- (1 until iNums.length))
            {
                iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
            }
            println(List(iMin, iNums(0), iNums.last).min)
        }
}

object Main
{
    def main(args:Array[String])
        {
            val n = readInt
            val iNums = (readLine + " 1000").split(" ").map(i => i.toInt)
            /*var iMin = 1001;
            for (i <- (1 until iNums.length))
            {
                iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
            }
            println(List(iMin, iNums(0), iNums.last).min)*/
            var iMin = (1 to n).map(i => List(iNums(i), iNums(i - 1)).max).min;
            println(List(iMin, iNums(0), iNums(n - 1)).min)
        }
}

object Main
{
	def main(args:Array[String])
		{
			val n = readInt
			val iNums = readLine.split(" ").map(i => i.toInt)
			/*var iMin = 1001;
			for (i <- (1 until iNums.length))
			{
				iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
			}
			println(List(iMin, iNums(0), iNums.last).min)*/
			var iMin = 1001;
			for (i <- (1 until iNums.length))
			{
				iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
			}
			println(List(iMin, iNums(0), iNums.last).min)
		}
}

object Main {
    def main(args: Array[String]) {

        val n = readInt
        val a = readLine.split(' ').map(_.toInt)

        val r = (1 to n).map(i => (i, a(i-1))).toArray.sortBy(_._2)

        var i = 1
        if(r(0)._1 != 1 && r(0)._1 != n) {
            while(i < n && r(i)._1 != 1 && r(i)._1 != n && r(i)._1 != r(i-1)._1+1) i += 1
            println(r(i)._2)
        } else {
            println(r(0)._1)
        }
    }
}

object Main {
    def main(args: Array[String]) {

        val n = readInt
        val a = readLine.split(' ').map(_.toInt)

        val r = (1 to n).map(i => (i, a(i-1))).toArray.sortBy(_._2)

        var i = 1
        if(r(0)._1 != 1 && r(0)._1 != n) {
            while(i < n && r(i)._1 != 1 && r(i)._1 != n && r(i)._1 != r(i-1)._1+1) i += 1
            println(r(i)._2)
        } else {
            println(r(0)._2)
        }
    }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val weight = in.next().split(' ').map(_.toInt)
  val order = in.next().split(' ').map(_.toInt - 1)
  var distinct = order.distinct.toList
  println(order.foldLeft(0) {
    case (acc, i) if distinct.head == i => acc
    case (acc, i) =>
      var sum = acc
      val firstPart = distinct.takeWhile(_ != i)
      val secondPart = distinct.dropWhile(_ != i).tail
      distinct = i :: (firstPart ::: secondPart)
      acc + firstPart.map(weight).sum
  })

}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val ws = readLongs(n)
  val bs = readInts(m).map(_ - 1)

  val first = Array.fill(n)(Int.MaxValue)
  for (i <- bs.indices) if (first(bs(i)) == Int.MaxValue) first(bs(i)) = i

  val stack = (0 until n).sortBy(first).toArray
  var res = 0L

  for (b <- bs) {
    var i = 0
  //println(b+1, stack.map(_ + 1).mkString(" "))
    while (stack(i) != b) {
      res += ws(stack(i))
      i += 1
    }
    while (i > 0) {
      stack(i) = stack(i - 1)
      i -= 1
    }
    stack(0) = b
  }

  println(res)
}

object P500C {
	@inline def readInts : Array[Int] = {
		scala.io.StdIn.readLine.split(" ").map(_.toInt)
	}

	def solve(ws: Array[Int])(s: List[Int], bs: List[Int]) : Int = {
		if (bs.isEmpty) {
			0
		} else {
			val (top, rest) = s.splitAt(s.indexOf(bs.head))
			val stack = rest.head :: top ::: rest.tail
			val lifted = top.foldLeft(0)((x, y) => x + ws(y - 1))
			lifted + solve(ws)(stack, bs.tail)
		}
	}

	def main(args: Array[String]) {
		val Array(n, m) = readInts
		val ws = readInts
		val bs = readInts.toList
		println(solve(ws)(bs.distinct, bs))
	}
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val weight = in.next().split(' ').map(_.toInt)
  val order = in.next().split(' ').map(_.toInt)
  var distinct = order.distinct.toList
  println(order.foldLeft(0) {
    case (acc, i) if distinct.head == i => acc
    case (acc, i) =>
      var sum = acc
      val firstPart = distinct.takeWhile(_ != i)
      val secondPart = distinct.dropWhile(_ != i).tail
      distinct = i :: (firstPart ::: secondPart)
      acc + firstPart.sum
  })

}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val ws = readLongs(n)
  val bs = readInts(m).map(_ - 1)

  val first = Array.fill(n)(-1)
  for (i <- bs.indices) if (first(bs(i)) < 0) first(bs(i)) = i

  val stack = (0 until n).sortBy(first).toArray
  var res = 0L

  for (b <- bs) {
    var i = 0
  //println(b+1, stack.map(_ + 1).mkString(" "))
    while (stack(i) != b) {
      res += ws(stack(i))
      i += 1
    }
    while (i > 0) {
      stack(i) = stack(i - 1)
      i -= 1
    }
    stack(0) = b
  }

  println(res)
}


import scala.io.StdIn

object ArrayStabilization extends App {

  val n = StdIn.readLine().toInt
  val xs = StdIn.readLine().split(" ").map(_.toInt)

  println(findSol(xs))

  def findSol(xs: Array[Int]) = {
    val revSorted = xs.sorted(Ordering[Int].reverse)

    val rem1 = revSorted.drop(1)
    val min1 = rem1.head - rem1.last

    val rem2 = revSorted.take(xs.length - 1)
    val min2 = rem2.head - rem2.last

    math.min(min1, min2)
  }
}

object CF_529_3_B {

  type In = (Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, xs) = in
    n match {
      case 2 => 0
      case _ =>
        val sort = xs.sorted
        val (min1, min2) = (sort(0), sort(1))
        val (max1, max2) = (sort.last, sort.init.last)
        if(min2 - min1 > max1 - max2) max1 - min2
        else max2 - min1
    }
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    sort(A)

    val ans = min(A(N - 1) - A(1), A(N - 2) - A(0))
    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.quickSort(a)
    a
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val setL, setR = mutable.Set[Int]()
    def findLMax: Int = {
      REP(N) { i =>
        if (setL.contains(A(i))) return i - 1
        setL += A(i)
      }
      N - 1
    }

    var ans = N
    val lMax = findLMax
    debug(s"lMax:$lMax")
    debug(setL.mkString(" "))
    var l = lMax
    var r = N
    while(l >= -1) {
      while(r - 1 > l && !setL.contains(A(r - 1)) && !setR.contains(A(r - 1))) {
        r -= 1
        setR += A(r)
      }
      debug(s"l:$l r:$r")
      ans = min(ans, r - l - 1)
      if (l >= 0) setL -= A(l)
      l -= 1
    }

    out.println(ans)
  }
}

import scala.collection.mutable

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = n
  var l = 0
  val left = mutable.Set.empty[Int]

  do {
    var r = 0
    val right = mutable.Set.empty[Int]
    if (l > 0) left += as(l - 1)
    do {
      if (n - r - l < min) {
        //println(l, r, left, right)
        min = n - r - l
      }
      if (r > 0) right += as(n - r)
      r += 1
    } while (l + r <= n && !left(as(n - r)) && !right(as(n - r)))
    l += 1
  } while (l < n && !left(as(l - 1)))

  println(min)
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val setL, setR = mutable.Set[Int]()
    def findLMax: Int = {
      REP(N) { i =>
        if (setL.contains(A(i))) return i - 1
        setL += A(i)
      }
      N - 1
    }

    var ans = N
    val lMax = findLMax
    debug(s"lMax:$lMax")
    debug(setL.mkString(" "))
    var l = lMax
    var r = N
    while(l >= 0) {
      while(r - 1 > l && !setL.contains(A(r - 1)) && !setR.contains(A(r - 1))) {
        r -= 1
        setR += A(r)
      }
      debug(s"l:$l r:$r")
      ans = min(ans, r - l - 1)
      setL -= A(l)
      l -= 1
    }

    out.println(ans)
  }
}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  val left = str.takeWhile(_ == '<').length
  val right = str.reverse.takeWhile(_ == '>').length
  println(Math.min(n, left + right))
}

object A725 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = scala.io.StdIn.readLine
    val right = input.reverse.dropWhile(_ == '>').length
    var res = input.length - right
    res += input.takeWhile(_ == '<').length
    println(res)
  }
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val _ = readLine
  val s = readLine.toCharArray

  val res = s.takeWhile(_ == '<').size + s.reverse.takeWhile(_ == '>').size

  //FIXME Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res)

  Console.flush
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _725A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    var b = read[String]
    b = b.dropWhile(_ == '<')
    b = b.reverse
    b = b.dropWhile(_ == '>')
    //debug(n, b.reverse)
    write(n - b.length)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object ReadInputExample {
def main(args: Array[String]): Unit = {
        var  d = scala.io.StdIn.readLine().toInt
        var  inp = scala.io.StdIn.readLine()
        val status = Array.fill[Option[Boolean]](inp.length)(None)
        for (i <- 0 until inp.length) {
            if (status(i).isEmpty) {
                isPossibleList(inp, i, status)
            }
        }
        println(status.filter(x => x.get).length)
    }
    def isPossibleList(inp: String, ind: Int, status: Array[Option[Boolean]]): Boolean = {
        if (status(ind).nonEmpty) return status(ind).get
        if ((ind == 0 && inp(ind) == '<') || (ind == inp.length - 1 && inp(ind) == '>')) {
            status(ind) = Some(true)
            return true
        }
        val res = if (inp(ind) == '>') {
            if (inp(ind + 1) == '<') false else isPossibleList(inp, ind + 1, status)
        } else {
            if (inp(ind - 1) == '>') false else isPossibleList(inp, ind - 1, status)
        }
        status(ind) = Some(res)
        res
    }
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

object ProblemA {
  def main(args: Array[String]): Unit = processStdInOut()

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val bumperCount = lines.next().toInt
    val bumpers = lines.next()
    val soln = solve(bumperCount, bumpers)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(bumperCount: Int, bumpers: String): Int = {
    @tailrec
    def countLeft(pos: Int, count: Int): Int =
      if (pos == bumperCount || bumpers(pos) == '>') count
      else countLeft(pos + 1, count + 1)

    @tailrec
    def countRight(pos: Int, count: Int): Int =
      if (pos == -1 || bumpers(pos) == '<') count
      else countRight(pos - 1, count + 1)

    val totalCount = countLeft(0, 0) + countRight(bumperCount - 1, 0)
    totalCount
  }
}

object JumpingBall extends App {

  import scala.util.control.Breaks._

  def execute(firstInput: Int, bumpers: String): Int = {

    var acc = 0
    val n = bumpers.length

    breakable {
      for(i <- 0 until n){
        if(bumpers(i) == '<') acc += 1
        else break
      }
    }

    breakable {
      for(i <- n - 1 to 0 by -1){
        if(bumpers(i) == '>') acc += 1
        else break
      }
    }

    acc

  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {
      val n = bumpers.length - 1

      val minRightIndex = bumpers.indexOf('>')
      val maxLeftIndex = bumpers.lastIndexOf('<')

      def sumIzq(ind: Int): Int =
        if(ind > 0 ) ind
        else 0

      def sumDer(ind: Int): Int =
        if(ind < n ) n - ind
        else 0

      if(minRightIndex == 0 && maxLeftIndex == n) 0 // >..<
      else if(minRightIndex == -1 && maxLeftIndex == n) sumIzq(maxLeftIndex) + 1 // <<<
      else if(maxLeftIndex == -1 && minRightIndex == 0) sumDer(minRightIndex) + 1 // >>>
      else sumIzq(minRightIndex) + sumDer(maxLeftIndex) // ..>..<..
  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {

    def sum(filter: Char => Boolean)(bumpers: List[Char], acc: Int): Int = bumpers match {
      case Nil => acc
      case x :: xs if filter(x) => acc
      case x :: xs => sum(filter)(xs, acc + 1)
    }

    def sumIzq = sum( _ == '>' ) _
    def sumDer = sum( _ == '<' ) _

    sumIzq(bumpers.toList, 0) + sumDer(bumpers.reverse.toList,  0)

  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {
      val n = bumpers.length - 1

      val minRightIndex = bumpers.indexOf('>')
      val maxLeftIndex = bumpers.lastIndexOf('<')

      def sumIzq(ind: Int): Int =
        if(ind > 0 ) ind
        else 0

      def sumDer(ind: Int): Int =
        if(ind < n ) n - ind
        else 0

      if(minRightIndex == 0 && maxLeftIndex == n) 0
      else sumIzq(minRightIndex) + sumDer(maxLeftIndex)
  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.read() // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {
      val n = bumpers.length - 1

      val minRightIndex = bumpers.indexOf('>')
      val maxLeftIndex = bumpers.lastIndexOf('<')

      def sumIzq(ind: Int): Int =
        if(ind > 0 ) ind
        else 0

      def sumDer(ind: Int): Int =
        if(ind < n ) n - ind
        else 0

      if(minRightIndex == 0 && maxLeftIndex == n) 0
      else sumIzq(minRightIndex) + sumDer(maxLeftIndex)
  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}


object B2 {
  import InOut._
  def main(args: Array[String]): Unit = {}

  /**
   * 1-based Binary Indexed (Fenwick) Tree with binary search.
   */
  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- src.indices) update(i + 1, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query(r - (r & -r), acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def firstGreaterOrEqual(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) < goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val n = nextInt
  val as = nextInts(n)
  val G = 1
  val sorted = as.sorted
  val sortedWithIndex = as.zipWithIndex.sortBy {
    case (x, i) => (-x, i)
  }
  val order = Array.ofDim[Int](n)
  for (i <- as.indices) {
    order(i) = sortedWithIndex(i)._2
  }

  val m = nextInt
  case class Query(k: Int, pos: Int, id: Int)
  val queries = Array.tabulate(m) { id =>
    val k, pos = nextInt
    Query(k, pos, id)
  }.sortBy(_.k)

  val res = Array.ofDim[Int](m)
  val bit = new BIT(Array.fill(n)(0L))

  var currentK = 0
  for (q <- queries) {
    while (currentK < q.k) {
      bit.update(order(currentK) + 1, +1)
      currentK += 1
    }
    val i = bit.firstGreaterOrEqual(q.pos) - 1
    res(q.id) = as(i)
  }

  out.println(res.mkString("\n"))
  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._
  case class Entry(a: Int, i: Int)
  case class Query(k: Int, pos: Int, m: Int)

  class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {
  def this(n: Int) = this(n, 0)(_ + _)

  private val N = {
    val a = Integer.highestOneBit(n)
    if (a == n) a else a << 1
  }
  private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)

  /**
    * 1 index
    * addとindex違うよ
    * cumsumなんかといっしょ
    */
  def sum(i: Int): Int = {
    assert(i <= n)
    var x = i
    var s: Int = zero
    while(x > 0) {
      s = f(s, bit(x))
      x -= x & -x
    }
    s
  }

  /**
    * 0 index
    */
  def add(i: Int, a: Int): Unit = {
    assert(i < n)
    var x = i + 1
    while(x <= N) {
      bit(x) = f(bit(x), a)
      x += x & -x
    }
  }

  def sumAll: Int = sum(n)

  // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
  private def sub(a: Int, b: Int) = a - b
  private def lt(a: Int, b: Int) = a < b

  /**
    * [l, r)
    */
  def query(l: Int, r: Int): Int = {
    assert(r > l)
    sub(sum(r), sum(l))
  }

  def lowerBound(W: Int): Int = {
    var k = N
    var x = 0
    var w = W
    while(k > 0) {
      if (x + k <= N && lt(bit(x + k), w)) {
        w = sub(w, bit(x + k))
        x += k
      }
      k /= 2
    }
    math.min(n, x)
  }
}
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val A = na(N)
    val E = Array.ofDim[Entry](N)
    REP(N) { i =>
      E(i) = Entry(A(i), i)
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = {
        if (o1.a == o2.a) Integer.compare(o1.i, o2.i)
        else Integer.compare(o2.a, o1.a) // 降順
      }
    })
    val M = ni()
    val queried = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())
    val ans = Array.ofDim[Int](M)
    REP(M) { m =>
      val k, pos = ni()
      val q = Query(k, pos, m)
      queried(k - 1) += q
    }

    val bit = new BIT(N)
    REP(N) { i =>
      bit.add(E(i).i, 1)
      queried(i).foreach { q =>
        val ix = bit.lowerBound(q.pos)
        ans(q.m) = A(ix)
      }
    }

    REP(M) { i =>
      out.println(ans(i))
    }
  }
}

object B2 {
  import InOut._
  def main(args: Array[String]): Unit = {}

  /**
   * 1-based Binary Indexed (Fenwick) Tree with binary search.
   */
  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- src.indices) update(i + 1, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query(r - (r & -r), acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def firstGreaterOrEqual(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) < goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val n = nextInt
  val as = nextInts(n)
  val G = 1
  val sorted = as.zipWithIndex.sortBy {
    case (x, i) => (x, -i)
  }
  val order = Array.ofDim[Int](n)
  for (i <- as.indices) {
    order(sorted(i)._2) = i
  }

  val m = nextInt
  case class Query(k: Int, pos: Int, id: Int)
  val queries = Array.tabulate(m) { id =>
    val k, pos = nextInt
    Query(k, pos, id)
  }.sortBy(_.k)

  val res = Array.ofDim[Int](m)
  val bit = new BIT(Array.fill(n)(0L))

  var currentK = 0
  for (q <- queries) {
    while (currentK < q.k) {
      bit.update(order(currentK) + 1, +1)
      currentK += 1
    }
    val i = bit.firstGreaterOrEqual(q.pos) - 1
    res(q.id) = as(i)
  }

  out.println(res.mkString("\n"))
  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val MOD = 1000000007L
  val MODB = BigInt(MOD)

  val v = mutable.Map.empty[(Int, Int), Long]

  val Array(h, w, n) = readInts(3)

  val fs, fInvs = Array.ofDim[Long](h + w)

  var f = 1L
  for (i <- fs.indices) {
    fs(i) = f
    fInvs(i) = BigInt(f).modInverse(MODB).toLong
    f = f * (i + 1) % MOD
  }

  def pascal(r: Int, c: Int): Long = {
    val k = r - 1
    val n = r + c - 2
    (fs(n) * fInvs(n - k) % MOD) * fInvs(k) % MOD
  }

  val black = Array.ofDim[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(r, c) = readInts(2)
    black(i) = (r, c)
  }

  val sorted = black.sorted

  for (i <- 0 until n) {
    val (r, c) = sorted(i)
    var d = pascal(r, c)
    for (j <- 0 until n) {
      val (r2, c2) = sorted(j)
      if (r2 <= r && c2 <= c && i != j) {
        d = (d + MOD - v(r2, c2) * pascal(r - r2 + 1, c - c2 + 1) % MOD) % MOD
      }
    }
    v += (r, c) -> d
  }

  var res = pascal(h, w)

  for (i <- 0 until n) {
    val (r, c) = sorted(i)
    res = (res + MOD - v(r, c) * pascal(h - r + 1, w - c + 1) % MOD) % MOD
  }

  println(res)
}

object C2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  //import scala.collection.mutable.Set
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }
    for(i<-2 until maxhw){
      inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum
    }
    inverseModuloTable(0)=1
    val prodModuloTable=Array.fill(maxhw*2)(1L)
    for(i<-2 until prodModuloTable.length){
      prodModuloTable(i)=(prodModuloTable(i-1)*i)%hugeNum
    }
    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=(prodModuloTable(n)*inverseModuloTable(n-m))%hugeNum

        ans=(ans*inverseModuloTable(m))%hugeNum

      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)

      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){

          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}

import io.StdIn._

object Solution {

  val mod: Long = 1000000007

  val maxn = 200000

  val fac = Array.fill(maxn+1)(1L)

  val inv = Array.fill(maxn+1)(1L)

  def main(args: Array[String]) {
    val line = readLine().split(" ").map(_.toInt)
    val (h, w, n) = (line(0), line(1), line(2))

    var black = Array.ofDim[(Int, Int)](n).map{ _ =>
      val line = readLine().split(" ").map(_.toInt)
      (line(0), line(1))
    }

    for (i <- 1 to maxn) {
      fac(i) = fac(i-1) * i % mod
      inv(i) = pow(fac(i), mod-2)
    }

    black = black.sorted ++ Array((h, w))

    val f = black.map( b => cab(1, 1, b._1, b._2) )

    for (
      (c, i) <- black.zipWithIndex;
      (p, j) <- black.take(i).zipWithIndex if c._1 >= p._1 && c._2 >= p._2
    ) {
      f(i) = (f(i) - (f(j) * cab(p._1, p._2, c._1, c._2) % mod) + mod) % mod
    }

    println(f(n))

  }

  private def pow(aa: Long, nn: Long): Long = {
    var (a, n) = (aa, nn)
    var res = 1L
    while (n > 0) {
      if ((n & 1) == 1) res = res * a % mod
      a = a * a % mod
      n >>= 1
    }
    res % mod
  }

  private def cab(ax: Int, ay: Int, bx: Int, by: Int): Long = {
    val m: Int = bx - ax + by - ay
    val n: Int = bx - ax
    fac(m) * inv(n) % mod * inv(m-n) % mod
  }

}

object C2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  //import scala.collection.mutable.Set
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }
    for(i<-2 until maxhw){
      inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum
    }

    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=1L
      for(i<-n-m+1 to n){
        ans=(ans*i)%hugeNum
      }

        ans=(ans*inverseModuloTable(m))%hugeNum

      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)
      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){
          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}

object C2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  //import scala.collection.mutable.Set
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }
    for(i<-1 until maxhw){
      inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum
    }
    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=1L
      for(i<-n-m+1 to n){
        ans=(ans*i)%hugeNum
      }

        ans=(ans*inverseModuloTable(m))%hugeNum

      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)
      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){
          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}

object C2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  //import scala.collection.mutable.Set
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }

    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=1L
      for(i<-n-m+1 to n){
        ans=(ans*i)%hugeNum
      }
      for(i<-1 to m){
        ans=(ans*inverseModuloTable(i))%hugeNum
      }
      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)
      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){
          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}