{-# LANGUAGE MultiWayIf #-}
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

po :: (Integral a) => a
po = 1000000007

main :: IO ()
main = do
  getLine
  t <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  a <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  let
    range [] _ = []
    range (x:xs) n = if x /= n then (x, 1):range xs x else (x, x):range xs x
    tt = range t 0
    aa = reverse $ range (reverse a) 0
    solve [] _ = 1
    solve _ [] = 1
    solve ((x, n):xs) ((y, m):ys) = if
      | n == 1 -> if (m == 1 && x == y) || x <= y then solve xs ys else 0
      | m == 1 -> if (n == 1 && x == y) || y <= x then solve xs ys else 0
      | otherwise -> min n m * solve xs ys `mod` po
  print $ solve tt aa
