main::IO()
main = do
  _<-getLine
  tc<-getLine
  let t_dat = map read (words tc) ::[Int]
  ac<-getLine
  let a_dat = map read (words ac) ::[Int]
  print (solver t_dat a_dat)


error_checker::[Int]->[Int]->Bool
error_checker t_dat a_dat = let t_max = maximum t_dat in
                            let a_max = maximum a_dat in
                            if a_max /= t_max then False
                                              else let zipped= zip t_dat a_dat in
                                                   let ls = dropWhile (\(t,a)-> (t==t_max)||(a==a_max)) zipped in
                                                   (ls == [])

solver::[Int]->[Int]->Int
solver t_dat a_dat = if error_checker t_dat a_dat == False then 0
                                                          else (subsolver (zip t_dat a_dat))

subsolver::[(Int,Int)]->Int
subsolver ta_dat = let (t_part,rest) = span (\(t,a)->t/=a) ta_dat in
                   let (same,a_part) = span (\(t,a)->t==a) rest   in
                   let a_part'       = reverse a_part             in
                   let t_p = map fst t_part  in
                   let a_p = map snd a_part' in
                   let s   = map fst same    in
                   mod ((mod ((product_1 0 t_p)*(product_1 0 a_p)) 1000000007)*(product_2 s)) 1000000007

product_1::Int->[Int]->Int
product_1 _   []     = 1
product_1 old (x:xs) = if old<x then product_1 x xs else mod (x * (product_1 x xs)) 1000000007

product_2::[Int]->Int
product_2 []      = 1
product_2 (_:[])  = 1
product_2 (_:_:[])= 1
product_2 (x:xs)  = mod (x*(product_2 xs)) 1000000007
