You are given two arrays $a_1, a_2, \dots , a_n$ and $b_1, b_2, \dots , b_m$. Array $b$ is sorted in ascending order ($b_i < b_{i + 1}$ for each $i$ from $1$ to $m - 1$).

You have to divide the array $a$ into $m$ consecutive subarrays so that, for each $i$ from $1$ to $m$, the minimum on the $i$-th subarray is equal to $b_i$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $a$ compose the first subarray, the next several elements of $a$ compose the second subarray, and so on.

For example, if $a = [12, 10, 20, 20, 25, 30]$ and $b = [10, 20, 30]$ then there are two good partitions of array $a$:   $[12, 10, 20], [20, 25], [30]$;  $[12, 10], [20, 20, 25], [30]$. 

You have to calculate the number of ways to divide the array $a$. Since the number can be pretty large print it modulo 998244353.


-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of arrays $a$ and $b$ respectively.

The second line contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 10^9$) — the array $a$.

The third line contains $m$ integers $b_1, b_2, \dots , b_m$ ($1 \le b_i \le 10^9; b_i < b_{i+1}$) — the array $b$.


-----Output-----

In only line print one integer — the number of ways to divide the array $a$ modulo 998244353.


-----Examples-----
Input
6 3
12 10 20 20 25 30
10 20 30

Output
2

Input
4 2
1 3 3 7
3 7

Output
0

Input
8 2
1 2 2 2 2 2 2 2
1 2

Output
7

Source: codeforces | Difficulty: HARD
Tags: Constructive algorithms

Combinatorics

Amortized analysis

Sorting

Complete search

Dynamic programming


Solutions:
import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n, m) = I()
a = I()
b = I()
an = 1
md = 998244353
suf = [0] * n
suf[-1] = a[n - 1]
for i in range(n - 2, -1, -1):
	suf[i] = min(suf[i + 1], a[i])
suf = [0] + suf
cr = m - 1
ct = 0
for i in range(n, -1, -1):
	if suf[i] < b[cr]:
		if ct == 0 or (i < n and suf[i + 1] != b[cr]):
			an = 0
			break
		if i == 0:
			cr -= 1
			break
		cr -= 1
		an = an * ct % md
		ct = 0
	if suf[i] == b[cr]:
		ct += 1
if ct == 0 or cr != -1:
	an = 0
print(an)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	(n, m) = rl()
	A = rl()
	B = rl()
	mod = 998244353
	if A[0] < B[0]:
		print(0)
		return
	mins = dd(int)
	_min = A[-1]
	for a in A[::-1]:
		_min = min(_min, a)
		mins[_min] += 1
	if _min != B[0]:
		print(0)
		return
	answer = 1
	for b in B[1:]:
		if mins[b] == 0:
			print(0)
			return
		else:
			answer = answer * mins[b] % mod
	print(answer)
mode = 'S'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 998244353
sol = 1
i = n - 1
j = m - 1
while sol > 0 and j >= 0:
	goal = b[j]
	s = 0
	r = False
	while i >= 0 and a[i] >= goal:
		if r:
			s += 1
		elif a[i] == goal:
			r = True
			s = 1
		i -= 1
	if j == 0:
		s = min(s, 1)
		if i >= 0:
			s = 0
	sol = sol * s
	sol = sol % mod
	j -= 1
print(sol)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def fi():
	return float(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
mod = 1000000007
mod2 = 998244353
from math import *
import bisect
from decimal import *
getcontext().prec = 25
abc = 'abcdefghijklmnopqrstuvwxyz'

def fn(n):
	c = 0
	while n % 2 == 0:
		c += 1
		n //= 2
	return c
pi = 3.141592653589793

def main():
	(n, m) = mi()
	a = li()
	b = li()
	if min(a) != b[0]:
		print(0)
		exit()
	if m == 1:
		if min(a) == b[0]:
			print(1)
		else:
			print(0)
		exit()
	ans = 1
	k = n - 1
	for i in range(m - 1, -1, -1):
		x = b[i]
		c = 0
		f = 0
		if i == 0:
			break
		for j in range(k, -1, -1):
			if a[j] < x:
				k = j
				break
			if f == 0 and a[j] == x:
				f = 1
				c = 1
			elif f and a[j] >= x:
				c += 1
		ans *= c
		ans %= mod2
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
(n, m) = map(int, input().split())
ans = 1
mod = 998244353
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i = n - 1
j = m - 1
while ans and j >= 0:
	cnt = 0
	while i >= 0 and a[i] >= b[j]:
		if cnt:
			cnt += 1
		elif a[i] == b[j]:
			cnt = 1
		i -= 1
	if j == 0:
		cnt = min(cnt, 1)
		if i >= 0:
			cnt = 0
	ans = ans * cnt % mod
	j -= 1
print(ans)


md = 998244353
(n, m) = map(int, input().split())
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))
mn = [0] * n
s = aa[-1]
(r, ans, l) = (n, 1, 0)
for i in range(n - 1, -1, -1):
	s = min(s, aa[i])
	mn[i] = s
for b in bb[::-1]:
	while r - 1 >= 0 and mn[r - 1] > b:
		r -= 1
	if r == 0 or mn[r - 1] != b:
		ans = 0
		break
	l = r - 1
	while l - 1 >= 0 and mn[l - 1] == b:
		l -= 1
	if l:
		ans = ans * (r - l) % md
	r = l
if l:
	ans = 0
print(ans)


mod = 998244353

def solv(A, B):
	ans = 1
	(ai, bi) = (len(A) - 1, len(B) - 1)
	cnt = 0
	match = False
	while ai >= 0 and bi >= 0:
		if match:
			if A[ai] >= B[bi]:
				cnt += 1
				ai -= 1
			else:
				ans = ans * cnt % mod
				match = False
				bi -= 1
				cnt = 0
		else:
			if A[ai] < B[bi]:
				return 0
			if A[ai] == B[bi]:
				match = True
				cnt = 1
			ai -= 1
	return ans if match and bi == 0 else 0
_ = input()
A = list(map(int, list(input().split())))
B = list(map(int, list(input().split())))
print(solv(A, B))


from sys import stdin, stdout
import collections, heapq, bisect, math
input = stdin.readline

def rint():
	return int(input())

def rstr():
	return input().strip()

def rlstr():
	return list(input().strip().split())

def rlint():
	return list(map(int, input().split()))

def main():
	(n, m) = rlint()
	a = rlint()
	b = rlint()
	mod = 998244353
	j = m - 1
	i = n - 1
	res = 1
	while j > 0:
		count = 0
		while i >= 0 and b[j] < a[i]:
			i -= 1
		while i >= 0 and b[j] <= a[i]:
			count += 1
			i -= 1
		j -= 1
		res = res * count % mod
	if i < 0 or min(a[:i + 1]) != b[0]:
		res = 0
	print(res)
main()


import sys, math
import io, os

def data():
	return sys.stdin.buffer.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
mod = 998244353
(n, m) = mdata()
a = mdata()
b = mdata()
d = {}
m1 = a[-1]
s = n - 1
for i in range(n - 2, -1, -1):
	if a[i] < m1:
		d[m1] = [s, i + 1]
		s = i
		m1 = a[i]
d[m1] = [s, 0]
if d.get(b[0]) == None:
	out(0)
	exit()
if d[b[0]][1] != 0:
	out(0)
	exit()
ans = 1
for i in range(m - 1):
	if d.get(b[i]) == None or d.get(b[i + 1]) == None:
		out(0)
		exit()
	ans = ans * (d[b[i + 1]][0] - d[b[i + 1]][1] + 1) % mod
out(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
(it, ans, c, d, M) = (m - 1, 0, [0] * m, [[0, 0] for i in range(m)], 998244353)
for i in range(n - 1, -1, -1):
	if it <= 0:
		break
	if a[i] < b[it]:
		if c[it]:
			(d[it][0], d[it - 1][1]) = (i + 1, i)
			it -= 1
		else:
			print(ans)
			exit()
	if a[i] == b[it]:
		c[it] += 1
(d[-1][-1], ans, ANS) = (n - 1, [1] * m, 1)
for i in range(m):
	if min(a[d[i][0]:d[i][1] + 1]) != b[i]:
		print('0')
		exit()
for i in range(m - 1):
	for j in range(d[i][1] + 1, d[i + 1][1]):
		if a[j] == b[i + 1]:
			c[i + 1] -= 1
		if c[i + 1]:
			ans[i] += 1
		else:
			break
	ANS = ANS % M * (ans[i] % M) % M
print(ANS)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
md = 998244353
(n, m) = MI()
aa = LI()
bb = LI()
mn = [0] * n
s = aa[-1]
for i in range(n - 1, -1, -1):
	s = min(s, aa[i])
	mn[i] = s
r = n
ans = 1
l = 0
for b in bb[::-1]:
	while r - 1 >= 0 and mn[r - 1] > b:
		r -= 1
	if r == 0 or mn[r - 1] != b:
		ans = 0
		break
	l = r - 1
	while l - 1 >= 0 and mn[l - 1] == b:
		l -= 1
	if l:
		ans = ans * (r - l) % md
	r = l
if l:
	ans = 0
print(ans)


from sys import stdin, stdout
from bisect import bisect_left, bisect_right
R = lambda : stdin.readline().strip()
RL = lambda : list(map(int, R().split(' ')))
output = lambda x: stdout.write(str(x))
(n, m) = RL()
a = RL()
b = RL()
M = 998244353
min_a = n * [a[-1]]
for i in range(n - 2, -1, -1):
	min_a[i] = min(a[i], min_a[i + 1])
if min_a[0] != b[0]:
	output(0)
	exit()
i = n - 1
ans = 1
for j in range(m - 1, 0, -1):
	count = 0
	while i > -1 and min_a[i] >= b[j]:
		if min_a[i] == b[j]:
			count += 1
		i -= 1
	if not count:
		output(0)
		exit()
	ans = ans * count % M
output(ans)


from collections import defaultdict

def read_list():
	return list(map(int, input().split(' ')))

def print_list(l):
	print(' '.join(map(str, l)))

def gcd(m, n):
	while n:
		(m, n) = (n, m % n)
	return m
(lena, lenb) = read_list()
a = read_list()
b = read_list()
ib = lenb - 1
ia = lena - 1
res = []
while ib >= 0 and ia >= 0:
	tmp = 0
	while ia >= 0 and a[ia] > b[ib]:
		ia -= 1
	if ia >= 0 and a[ia] == b[ib]:
		while ia >= 0 and a[ia] >= b[ib]:
			tmp += 1
			ia -= 1
	if tmp > 0:
		res.append((ia, ia + tmp))
	else:
		break
	ib -= 1
if len(res) < lenb or res[-1][0] != -1:
	print(0)
else:
	ans = 1
	for r in res[:-1]:
		ans *= r[1] - r[0]
	print(ans % 998244353)


import sys
input = sys.stdin.readline
from bisect import bisect_left, bisect_right
MOD = 998244353
(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
if any((v < B[0] for v in A)):
	print(0)
	sys.exit(0)
p = 10 ** 10
curr = 0
i = m - 1
r = 1
for v in reversed(A):
	v = min(v, p)
	j = bisect_right(B, v) - 1
	if j == i:
		if v == B[j]:
			curr += 1
		else:
			curr = 0
	elif j == i - 1:
		if p == B[i]:
			r = r * curr % MOD
		else:
			print(0)
			sys.exit(0)
		curr = 1 if v == B[j] else 0
		i = j
	else:
		print(0)
		sys.exit(0)
	p = v
print(r if i == 0 and curr else 0)


import math
(n, m) = tuple(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ai = n - 1
bi = m - 1
num_split = [0] * m
while bi >= 0:
	while ai >= 0 and a[ai] > b[bi]:
		ai -= 1
	while ai >= 0 and a[ai] >= b[bi]:
		num_split[bi] += 1
		ai -= 1
	bi -= 1
if ai >= 0:
	num_split[0] = 0
if num_split[0] > 0:
	print(math.prod(num_split[1:]) % 998244353)
else:
	print(0)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
from math import inf
for _ in range(int(input()) if not True else 1):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if m > n:
		print(0)
		quit()
	if m == n:
		print(1 if a == b else 0)
		quit()
	mod = 998244353
	(i, j) = (n - 1, m - 1)
	ans = 1
	while j + 1:
		if not ans:
			break
		found = False
		cover = 0
		while i + 1 and a[i] >= b[j]:
			if not found and a[i] == b[j]:
				found = True
				cover += 1
			elif found:
				cover += 1
			i -= 1
		if j == 0:
			cover = min(cover, 1)
			if i + 1:
				cover = 0
		ans = ans * cover % mod
		j -= 1
	print(ans)


import sys
input = sys.stdin.buffer.readline

def prog():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	R = [0 for i in range(m - 1)]
	L = [0 for i in range(m - 1)]
	idx = n - 1
	fail = False
	i = 1
	for i in range(m - 1, 0, -1):
		right = b[i]
		left = b[i - 1]
		while a[idx] != right:
			if idx == 0 or a[idx] < right:
				fail = True
				break
			idx -= 1
		if fail:
			break
		else:
			idx -= 1
			if idx == -1:
				fail = True
				break
			R[i - 1] = idx
			while a[idx] >= right:
				if idx == 0:
					fail = True
					break
				idx -= 1
			if a[idx] < left:
				fail = True
			if fail:
				break
			else:
				L[i - 1] = idx
		if fail:
			break
	if i == 1 and fail == False:
		fail = True
		last = b[0]
		for i in range(idx, -1, -1):
			if a[i] == last:
				fail = False
			elif a[i] < last:
				fail = True
				break
	if fail:
		print(0)
	else:
		total = 1
		for i in range(m - 1):
			total = total * (R[i] - L[i] + 1) % 998244353
		print(total)
prog()


import sys
input = lambda : sys.stdin.readline().rstrip()
(n, m) = map(int, input().split())
A = [int(i) for i in input().split()][::-1]
B = [int(i) for i in input().split()][::-1]
mod = 998244353
cur = 0
ct = 0
Chk = False
Ans = [0] * (m - 1)
ans = 1
for i in range(n):
	if A[i] > B[cur] and Chk == False:
		continue
	elif A[i] == B[cur] and Chk == False:
		Chk = True
		ct = 1
	elif A[i] < B[cur] and Chk == False:
		ans = 0
	elif A[i] >= B[cur]:
		ct += 1
	elif A[i] < B[cur] and cur == m - 1:
		ans = 0
	else:
		Ans[cur] = ct
		ct = 0
		Chk = False
		if cur + 1 <= m - 1 and A[i] == B[cur + 1]:
			ct = 1
			Chk = True
		elif A[i] < B[cur + 1]:
			ans = 0
		cur += 1
if not Chk:
	print(0)
elif m == 1:
	if min(A) == B[0]:
		print(1)
	else:
		print(0)
else:
	for a in Ans:
		ans = ans * a % mod
	print(ans)


def main():
	(n, m) = map(int, input().split())
	(aa, bb) = (list(map(int, input().split())) for _ in 'ab')
	(res, term, i, start) = (1, bb[0], n - 1, 0)
	for b in reversed(bb):
		while i >= 0 and aa[i] > b:
			i -= 1
		if i >= 0 and aa[i] == b:
			start = i
		else:
			res = 0
			break
		while i >= 0 and aa[i] >= b:
			i -= 1
		if b == term:
			break
		res = res * (start - i) % 998244353
	print(res * (i < 0))
main()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 998244353
ans = 1
i = n - 1
j = m - 1
while j >= 0:
	count = 0
	while i >= 0 and a[i] >= b[j]:
		if count > 0:
			count += 1
		elif a[i] == b[j]:
			count = 1
		i -= 1
	if j == 0:
		if count > 0:
			count = 1
		if i >= 0:
			count = 0
	ans *= count
	ans %= mod
	j -= 1
print(ans)


import math
(m, n) = tuple(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a1 = m - 1
b1 = n - 1
num_split = [0] * (n - 1)
while b1 > 0:
	while a[a1] > b[b1]:
		a1 -= 1
	while a1 >= 0 and a[a1] >= b[b1]:
		num_split[b1 - 1] += 1
		a1 -= 1
	b1 -= 1
while a1 >= 0:
	if a[a1] < b[b1]:
		print(0)
		exit(0)
	a1 -= 1
else:
	if a.count(b[b1]) == 0:
		print(0)
	else:
		print(math.prod(num_split) % 998244353)


mod = 998244353
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	A_unique = sorted(list(set(A)))
	A_set = set(A)
	B_set = set(B)
	if A_unique[0] not in B_set:
		print(0)
		exit()
	for b in B:
		if b not in A_set:
			print(0)
			exit()
	B_set.remove(A_unique[0])
	pos = {}
	for (i, a) in enumerate(A):
		pos[a] = i
	ans = 1
	r = -1
	for a in A_unique:
		if a in B_set:
			i = pos[a]
			if i < r:
				print(0)
				exit()
			ans = ans * (i - r) % mod
		r = max(r, pos[a])
	print(ans)
main()


from sys import stdin
input = stdin.readline
(n, m) = [int(x) for x in input().strip().split()]
a = [int(x) for x in input().strip().split()]
b = [int(x) for x in input().strip().split()]
MOD = 998244353
ans = 1
(ai, bi) = (n - 1, m - 1)
while bi >= 0:
	while ai >= 0 and a[ai] != b[bi]:
		if a[ai] < b[bi]:
			ans = 0
			bi -= 1
			break
		ai -= 1
	else:
		cur_start = ai
		while ai >= 0 and a[ai] >= b[bi]:
			ai -= 1
		cur_end = ai
		if bi:
			ans *= cur_start - cur_end
		elif ai >= 0 or cur_start - cur_end == 0:
			ans = 0
		ans %= MOD
		bi -= 1
print(ans)


(a, b) = map(int, input().split())
answer = 1
mod = 998244353
z = list(map(int, input().split()))
x = list(map(int, input().split()))
i = a - 1
j = b - 1
while answer and j >= 0:
	c = 0
	while i >= 0 and z[i] >= x[j]:
		if c:
			c += 1
		elif z[i] == x[j]:
			c = 1
		i -= 1
	if j == 0:
		c = min(c, 1)
		if i >= 0:
			c = 0
	answer = answer * c % mod
	j -= 1
print(answer)


import sys
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
last = []
i = n - 1
j = m - 1
MOD = 998244353
failflag = 0
while j >= 0 and i >= 0:
	r = b[j]
	while i >= 0:
		if a[i] == r:
			last.append(i)
			break
		if a[i] < r:
			failflag = 1
			break
		i -= 1
	if i < 0:
		break
	j -= 1
last.reverse()
if len(last) != m:
	print(0)
	return
for i in range(last[0]):
	if a[i] < b[0]:
		failflag = 1
if failflag == 1:
	print(0)
	return
ans = 1
for i in range(1, m):
	for j in range(last[i], last[i - 1] - 1, -1):
		if a[j] < b[i]:
			break
	ans = (last[i] - j) * ans % MOD
print(ans)


import sys
input = sys.stdin.buffer.readline

def getAnswer(a, b):
	a = list(reversed(a))
	b = list(reversed(b))
	if len(b) == 1:
		if min(a) == b[0]:
			return 1
		else:
			return 0
	res = 1
	x = 0
	y = 0
	j = 0
	while True:
		found = False
		for x in range(y, len(a)):
			if a[x] < b[j]:
				return 0
			if a[x] == b[j]:
				found = True
				break
		if found == False:
			return 0
		found = False
		for y in range(x, len(a)):
			if a[y] < b[j + 1]:
				return 0
			if a[y] == b[j + 1]:
				found = True
				break
		if found == False:
			return 0
		for mid in range(x, y + 1):
			if a[mid] < b[j]:
				break
		res *= mid - x
		res %= 998244353
		j += 1
		if j == len(b) - 1:
			break
	if min(a[y:]) < b[-1]:
		return 0
	return res
(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
print(getAnswer(a, b) % 998244353)


MOD = 998244353
(n, m) = map(int, input().split())
d = dict()
a = [0] + list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(m):
	d[b[i]] = i
c = [-1] * m
for (i, x) in enumerate(a):
	if x in d:
		c[d[x]] = i
idx = n
ans = 1
for i in range(m - 1, -1, -1):
	while b[i] <= a[idx]:
		idx -= 1
	if c[i] <= idx:
		print(0)
		exit(0)
	if i > 0:
		ans *= c[i] - idx
	elif idx > 0:
		print(0)
		exit(0)
	ans %= MOD
print(ans)


import sys
pprint = lambda s: print(' '.join(map(str, s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 998244353
suf_min = [(10000000000, -1)]
a_r = list(reversed(a))
for i in range(n):
	if a_r[i] < suf_min[-1][0]:
		suf_min.append((a_r[i], n - i - 1))
	else:
		suf_min.append(suf_min[-1])
suf_min.reverse()
if suf_min[0][0] != b[0]:
	print(0)
	exit(0)
ans = 1

def bin(a):
	l = 0
	r = n + 1
	while r - l > 1:
		m = (r + l) // 2
		if suf_min[m][0] > a:
			r = m
		else:
			l = m
	return l
for k in range(m - 1):
	j = bin(b[k + 1])
	if suf_min[j][0] != b[k + 1]:
		print(0)
		exit(0)
	ans = ans * (suf_min[j][1] - suf_min[bin(b[k + 1] - 1)][1]) % mod
print(ans)


import sys
input = sys.stdin.readline
t = 1
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	if min(a) != b[0]:
		print(0)
		exit(0)
	ff = {}
	for i in range(n - 1, -1, -1):
		if a[i] not in ff:
			ff[a[i]] = i
	d = [0 for i in range(n + 1)]
	st = []
	for i in range(n - 1, -1, -1):
		if len(st) == 0:
			st.append([a[i], i])
		else:
			while len(st) > 0 and st[-1][0] > a[i]:
				d[st[-1][1]] = i
				st.pop()
			st.append([a[i], i])
	while len(st):
		d[st[-1][1]] = -1
		st.pop()
	mod = 998244353
	g = {}
	for i in b:
		g[i] = 1
	for i in range(n):
		if len(st) == 0:
			st.append([a[i], i])
		else:
			while len(st) > 0 and st[-1][0] > a[i]:
				if st[-1][0] in g and ff[st[-1][0]] == st[-1][1]:
					print(0)
					exit(0)
				st.pop()
			st.append([a[i], i])
	c = 1
	for i in range(1, m):
		if b[i] not in ff:
			print(0)
			exit(0)
		c = c * (-d[ff[b[i]]] + ff[b[i]]) % mod
	print(c)


import os
os_input = os.read(0, int(10000000.0)).split()
os_input_pos = -1
answer_list = []

def read_s():
	global os_input_pos
	os_input_pos += 1
	return os_input[os_input_pos].decode()

def read_i():
	return int(read_s())

def write_s(v):
	answer_list.append(v)

def write_i(v):
	write_s(str(v))

def print_ans():
	os.write(1, '\n'.join(answer_list).encode())
	os.write(1, '\n'.encode())
from bisect import bisect
n = read_i()
m = read_i()
a = [read_i() for i in range(n)]
b = [read_i() for i in range(m)]
last = [-1 for i in range(2 * m + 2)]
for i in range(n):
	v = bisect(b, a[i])
	a[i] = 2 * v + 1 if v == 0 or a[i] > b[v - 1] else 2 * v
	last[a[i]] = i
MOD = 998244353
ans = int(last[1] == -1 and last[2] != -1)
for i in range(1, m):
	if last[2 * i] == -1 or last[2 * i + 2] <= last[2 * i]:
		ans = 0
	l = max(last[2 * i], last[2 * i + 1])
	r = last[2 * i + 2]
	if l >= r:
		ans = 0
	else:
		ans = ans * (r - l) % MOD
write_i(ans)
print_ans()


from sys import stdin, stdout

def two_arrasy(n, m, a, b):
	r = n - 1
	res = 1
	for i in range(m - 1, -1, -1):
		while r >= 0 and a[r] > b[i]:
			r -= 1
		if r < 0 or b[i] != a[r]:
			return 0
		l = r
		while l >= 0 and a[l] >= b[i]:
			l -= 1
		if l < 0 and i != 0:
			return 0
		if i == 0:
			if l >= 0 and a[l] < b[i]:
				return 0
			else:
				break
		res *= r - l
		res %= 998244353
		r = l
	return res
(n, m) = list(map(int, stdin.readline().split()))
a = list(map(int, stdin.readline().split()))
b = list(map(int, stdin.readline().split()))
res = two_arrasy(n, m, a, b)
stdout.write(str(res) + '\n')


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))

def solve():
	M = 998244353
	res = 1
	i = n - 1
	j = m - 1
	while j >= 0 and res:
		count = 0
		while i >= 0 and a[i] >= b[j]:
			if count > 0:
				count += 1
			elif a[i] == b[j]:
				count = 1
			i -= 1
		if j == 0:
			count = min(count, 1)
			if i >= 0:
				count = 0
		res *= count
		res %= M
		j -= 1
	return res
print(solve())


(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
c = [0 for _ in range(n)]
mn = a[-1]
for i in range(n - 1, -1, -1):
	mn = min(mn, a[i])
	c[i] = mn
j = n - 1
r = 1
for i in range(m - 1, -1, -1):
	k = 0
	while j >= 0 and c[j] > b[i]:
		j -= 1
	if j < 0 or c[j] != b[i]:
		r = 0
		break
	while j >= 0 and c[j] == b[i]:
		k += 1
		j -= 1
	if i != 0:
		r = r * k % 998244353
if j != -1:
	print(0)
else:
	print(r)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 998244353

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k))))
from collections import deque, defaultdict
import heapq

def solution(a, b, n, m):
	res = 1
	cnt = 0
	sa = set(a)
	sb = set(b)
	if not sb.issubset(sa):
		return 0
	curr_bi = 0
	d = defaultdict(int)
	for i in range(n):
		x = a[i]
		if x in sb:
			d[x] = i
	for i in range(m - 1):
		if d[b[i]] > d[b[i + 1]]:
			return 0
	first_index = 0
	for i in range(n):
		if a[i] < b[0]:
			return 0
		if a[i] == b[0]:
			first_index = i
			break
	curr_min_i = 0
	sol = 1
	check = True
	if len(b) == 1:
		check = False
	for i in range(first_index, n):
		x = a[i]
		if x < b[curr_min_i]:
			return 0
		if x == b[m - 1] and i == d[x]:
			curr_min_i = m - 1
			sol = sol * (cnt + 1) % NUMBER
			check = False
		if not check:
			continue
		if x == b[curr_min_i + 1] and i == d[b[curr_min_i + 1]]:
			curr_min_i += 1
			sol = sol * (cnt + 1) % NUMBER
			cnt = 0
		if i > d[b[curr_min_i]]:
			if x < b[curr_min_i + 1]:
				cnt = 0
			if x >= b[curr_min_i + 1]:
				cnt += 1
	return sol

def main():
	T = 1
	for i in range(T):
		(n, m) = ria()
		a = ria()
		b = ria()
		x = solution(a, b, n, m)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = dict()
for j in range(n):
	d[a[j]] = j
j = 0
f = 0
k = b[0]
if k in d.keys():
	p = d[k]
	q = p
	i = p
	while i >= 0:
		if a[i] < k:
			f = -1
			break
		i += -1
else:
	f = -1
if f != -1:
	res = 1
	j = 1
	while j < m:
		k = b[j]
		if k in d.keys():
			p = d[k]
			if p <= q:
				f = -1
				break
			else:
				i = p
				flag = 0
				while i > q:
					if a[i] < k and a[i] > b[j - 1] and (flag == 0):
						res *= (p - i) % 998244353
						flag = 1
					if a[i] < b[j - 1]:
						f = -1
						break
					i += -1
				if f == -1:
					break
				elif flag == 0:
					res *= (p - i) % 998244353
				q = p
		else:
			f = -1
			break
		j += 1
s = b[-1]
if s in d.keys():
	i = d[s]
	while i < n:
		if a[i] < s:
			f = -1
			break
		i += 1
else:
	f = -1
if f == -1:
	print(0)
else:
	print(res % 998244353)


def binaryfun(x, arr):
	low = 0
	high = len(arr) - 1
	mid = 0
	while low <= high:
		mid = (high + low) // 2
		if arr[mid] < x:
			low = mid + 1
		elif arr[mid] > x:
			high = mid - 1
		else:
			return mid
	return -1
inp = list(map(int, input().split()))
n = inp[0]
m = inp[1]
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))
if min(list1) < list2[0]:
	print(0)
else:
	ans = 0
	check = [-1] * m
	j = 0
	for i in range(n):
		index = binaryfun(list1[i], list2)
		if index != -1:
			check[index] = i
	ans = 0
	if -1 in check:
		print(0)
	else:
		if check == sorted(check):
			ans = 1
			for i in range(m - 1):
				temp = check[i]
				for j in range(check[i] + 1, check[i + 1]):
					if list1[check[i]] < list1[j] < list1[check[i + 1]]:
						temp = j
					elif list1[j] < list1[check[i + 1]]:
						ans = 0
						break
				if ans == 0:
					break
				check[i] = temp
				ans = ans * (check[i + 1] - check[i])
			templist = list1[check[-1]:]
			for i in templist:
				if i < list1[check[-1]]:
					ans = 0
					break
		print(ans % 998244353)


(n, s) = map(int, input().split())
res = 1
mod = 998244353
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i = n - 1
j = s - 1
while res and j >= 0:
	cnt = 0
	while i >= 0 and a[i] >= b[j]:
		if cnt:
			cnt += 1
		elif a[i] == b[j]:
			cnt = 1
		i -= 1
	if j == 0:
		cnt = min(cnt, 1)
		if i >= 0:
			cnt = 0
	res = res * cnt % mod
	j -= 1
print(res)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
MOD = 998244353
out = 1
first = -1
curr = m - 1
for i in range(n - 1, -1, -1):
	while a[i] < b[curr]:
		if first > -1:
			out *= first - i
			out %= MOD
		else:
			out = 0
		first = -1
		curr -= 1
		if curr < 0:
			out = 0
			break
	if a[i] == b[curr] and first == -1:
		first = i
if curr == 0 and first != -1:
	print(out)
else:
	print(0)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return flag

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None
t = 1
for i in range(t):
	(n, m) = RL()
	a = RLL()
	b = RLL()
	mod = 998244353
	ind = [0] * m
	ans = 0
	j = m - 1
	f = 1
	for i in range(n - 1, -1, -1):
		if j >= 0:
			if a[i] < b[j]:
				f = 0
				break
			elif a[i] == b[j]:
				ind[j] = i
				j -= 1
		elif a[i] < b[0]:
			f = 0
			break
	if j != -1:
		f = 0
	if f:
		ans = 1
		for i in range(m - 1):
			for j in range(ind[i + 1], -1, -1):
				if a[j] < b[i + 1]:
					break
			tmp = ind[i + 1] - j
			ans = tmp * ans % mod
	print(ans)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

class Node:

	def _init_(self, val):
		self.data = val
		self.left = None
		self.right = None

def pre_sum(arr):
	p = [0]
	for i in arr:
		p.append(p[-1] + i)
	p.pop(0)
	return p

def pre_back(arr):
	p = [0]
	for i in arr:
		p.append(p[-1] + i)
	p.pop(0)
	return p

def bin_search(arr, l, r, val):
	if arr[r] <= val:
		return r + 1
	if r - l < 2:
		if arr[l] > val:
			return l
		else:
			return r
	mid = int((l + r) / 2)
	if arr[mid] <= val:
		return bin_search(arr, mid, r, val)
	else:
		return bin_search(arr, l, mid, val)

def search_leftmost(arr, val):

	def helper(arr, l, r, val):
		print(l, r)
		if arr[l] == val:
			return l
		if r - l <= 1:
			if arr[r] == val:
				return r
			else:
				print('not found')
				return
		mid = int((r + l) / 2)
		if arr[mid] >= val:
			return helper(arr, l, mid, val)
		else:
			return helper(arr, mid, r, val)
	return helper(arr, 0, len(arr) - 1, val)

def search_rightmost(arr, val):

	def helper(arr, l, r, val):
		print(l, r)
		if arr[r] == val:
			return r
		if r - l <= 1:
			if arr[l] == val:
				return r
			else:
				print('not found')
				return
		mid = int((r + l) / 2)
		if arr[mid] > val:
			return helper(arr, l, mid, val)
		else:
			return helper(arr, mid, r, val)
	return helper(arr, 0, len(arr) - 1, val)

def preorder_postorder(root, paths, parent, left, level):
	l = 0
	queue = [root]
	while queue != []:
		node = queue[-1]
		flag = 0
		for i in paths[node]:
			if i != parent[node] and level[i] == sys.maxsize:
				parent[i] = node
				level[i] = level[node] + 1
				flag = 1
				queue.append(i)
		if flag == 0:
			left[parent[node]] += 1 + left[node]
			queue.pop()
	return [parent, left, level]

def nCr(n, r, p):
	if r == 0:
		return 1
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def f_exp(p, k0, k1, l):
	ans = 1
	k = k0 - k1
	while k != 0:
		if k % 2 == 0:
			k = k // 2
			p = p * p
		else:
			ans = ans * p
			k = (k - 1) // 2
			p = p * p
		if ans > l:
			ans = -1
			break
	return ans

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = 1
	mod = 998244353
	limit = 10 ** 18
	ans = 0
	for test in range(tests):
		[n, m] = inlt()
		a = inlt()
		b = inlt()
		last = {}
		for i in b:
			last[i] = -1
		for i in range(len(a)):
			if a[i] in last:
				last[a[i]] = i
		ans = 1
		flag = 0
		for i in range(1, m):
			if last[b[i]] == -1 or last[b[i - 1]] == -1:
				flag = 1
				break
			if last[b[i]] < last[b[i - 1]]:
				flag = 1
				break
			dec = 0
			f = 0
			for j in range(last[b[i]], last[b[i - 1]], -1):
				if dec == 0 and a[j] < b[i]:
					ans = ans * f % mod
					dec = 1
				if a[j] < b[i - 1]:
					flag = 1
					break
				f = f + 1
			if dec == 0:
				ans = ans * f % mod
			if flag == 1:
				break
		if flag != 1:
			for i in range(last[b[-1]], len(a)):
				if a[i] < b[-1]:
					flag = 1
					break
		if min(a) < b[0]:
			print(0)
		elif len(b) == 1:
			if b[0] not in a:
				print(0)
			else:
				print(1)
		elif flag == 1:
			print(0)
		else:
			print(ans)
main()


from sys import stdin
input = stdin.buffer.readline
(n, m) = map(int, input().split())
(*a,) = map(int, input().split())
(*b,) = map(int, input().split())
p = n - 1
mn = 10 ** 9 + 7
ans = 1
for i in range(m - 1, 0, -1):
	if mn < b[i]:
		exit(print(0))
	idx = -1
	while p >= 0:
		if idx == -1 and a[p] == b[i]:
			idx = p
		if a[p] < b[i]:
			break
		p -= 1
	mn = min(mn, a[p])
	if idx == -1 or p == -1:
		exit(print(0))
	ans *= idx - p
	ans %= 998244353
if min(a[:p + 1]) == b[0]:
	print(ans)
else:
	print(0)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
n -= 1
m -= 1
while n >= 0 and b[m] != a[n]:
	if b[m] > a[n]:
		print(0)
		exit(0)
	n -= 1
if n < 0 < m:
	print(0)
	exit(0)
ans = 1
mod = 998244353
while m >= 0 and n >= 0:
	sana = 0
	while n >= 0 and a[n] >= b[m]:
		sana += 1
		n -= 1
	if m:
		ans = ans * sana % mod
	m -= 1
	while n >= 0 and b[m] != a[n]:
		if b[m] > a[n]:
			print(0)
			exit(0)
		n -= 1
	if n < 0 < m:
		print(0)
		exit(0)
print(ans if n < 0 and m < 0 else 0)


(alen, blen) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
minIndex = [-1] * blen
curMinIndex = blen - 1
failCount = 0
MOD = 998244353
for i in range(alen - 1, -1, -1):
	if curMinIndex >= 0 and a[i] == b[curMinIndex]:
		minIndex[curMinIndex] = i
		curMinIndex -= 1
	elif curMinIndex >= 0 and a[i] < b[curMinIndex]:
		failCount = 1
		break
	elif curMinIndex == -1 and a[i] < b[0]:
		failCount = 1
		break
for val in minIndex:
	if val == -1:
		failCount = 1
if failCount == 1:
	print(0)
elif blen == 1:
	print(1)
else:
	rightExtensionAmount = [0] * (blen - 1)
	curMinIndex = 0
	for i in range(alen):
		if rightExtensionAmount[curMinIndex] == 0 and a[i] >= b[curMinIndex + 1]:
			rightExtensionAmount[curMinIndex] = minIndex[curMinIndex + 1] - i + 1
		if a[i] < b[curMinIndex + 1]:
			rightExtensionAmount[curMinIndex] = 0
		if i >= minIndex[curMinIndex + 1]:
			curMinIndex += 1
			if curMinIndex == blen - 1:
				break
	ans = 1
	for val in rightExtensionAmount:
		ans = ans * val % MOD
	print(ans)


mod = 998244353
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 1
i = n - 1
for j in range(m - 1, -1, -1):
	(l, r) = (-1, -1)
	while i != -1:
		if a[i] < b[j]:
			print(0)
			exit()
		if a[i] == b[j]:
			r = i
			break
		i -= 1
	else:
		print(0)
		exit()
	while i != -1:
		if a[i] < b[j]:
			l = i + 1
			if j == 0:
				print(0)
				exit()
			break
		i -= 1
	else:
		if j != 0:
			print(0)
			exit()
	if j != 0:
		ans *= r - l + 1
		ans %= mod
print(ans)


import sys
input = sys.stdin.readline
import bisect
mod = 998244353
(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
X = []
for a in A:
	X.append(bisect.bisect_right(B, a))
for i in range(n - 2, -1, -1):
	X[i] = min(X[i], X[i + 1])
R = [-1] * (m + 1)
L = [-1] * (m + 1)
if X[0] != 1:
	print(0)
	sys.exit()
for i in range(n):
	k = X[i]
	if L[k] == -1:
		L[k] = i
	if A[i] == B[k - 1]:
		R[k] = i
ANS = 1
for i in range(1, m + 1):
	if R[i] == -1 or L[i] == -1:
		print(0)
		sys.exit()
	if i == 1:
		continue
	ANS = ANS * (R[i] - L[i] + 1) % mod
print(ANS)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sorted(set(a + b))
ind = defaultdict(int)
t = 1
for i in sorted(s):
	ind[i] = t
	t += 1
for i in range(n):
	a[i] = ind[a[i]]
for i in range(m):
	b[i] = ind[b[i]]
ma = [-1] * (n + m + 1)
for i in range(n):
	ma[a[i]] = max(ma[a[i]], i)
s = SegmentTree(ma)
ans = 1
if b[0] != min(a):
	print(0)
	sys.exit(0)
for i in range(1, m):
	last = s.query(0, b[i] - 1)
	if last > ma[b[i]] or ma[b[i]] == -1:
		ans = 0
		break
	else:
		ans *= (ma[b[i]] - last) % mod1
		ans %= mod1
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, m) = RL()
	arra = RLL()
	arrb = RLL()
	lst = [-1] * m
	ind = m - 1
	for i in range(n - 1, -1, -1):
		now = arra[i]
		if ind >= 0 and now == arrb[ind]:
			lst[ind] = i
			ind -= 1
	res = 1
	tag = True
	lst = [lst[0]] + lst + [lst[-1]]
	for i in range(1, len(lst)):
		now = lst[i]
		if i == len(lst) - 1:
			now = n
		if now == -1:
			tag = False
			break
		ct = 1
		for j in range(lst[i - 1] if i - 1 != 0 else 0, now):
			pre = arra[j]
			if pre < arra[lst[i - 1]]:
				tag = False
			if pre < arra[lst[i]]:
				ct = 1
			else:
				ct += 1
		if tag == False:
			break
		if len(lst) - 1 > i > 1:
			res = res * ct % mod
	if tag:
		print(res % mod)
	else:
		print(0)
main()


from math import sqrt
it = lambda : list(map(int, input().strip().split()))
INF = float('inf')
MOD = 998244353

def solve():
	(n, m) = it()
	A = it()
	B = it()
	M = []
	j = n - 1
	for i in range(m - 1, -1, -1):
		c = 0
		ok = True
		while j >= 0 and A[j] != B[i]:
			if i + 1 < m and A[j] < B[i + 1]:
				ok = False
			if A[j] < B[i]:
				return 0
			if ok:
				c += 1
			j -= 1
		if j < 0:
			return 0
		assert A[j] == B[i]
		M.append(c)
		j -= 1
	while j >= 0:
		if A[j] < B[0]:
			return 0
		j -= 1
	a = 1
	for i in range(1, len(M)):
		a *= M[i] + 1
		if a > MOD:
			a %= MOD
	return a
print(solve())


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 1
m = a[-1]
mod = 998244353
ml = [0] * n
for i in range(n - 1, -1, -1):
	m = min(m, a[i])
	ml[i] = m
r = n
l = 0
for temp in b[::-1]:
	while r - 1 >= 0 and ml[r - 1] > temp:
		r -= 1
	if r == 0 or ml[r - 1] != temp:
		ans = 0
		break
	l = r - 1
	while l - 1 >= 0 and ml[l - 1] == temp:
		l -= 1
	if l:
		ans = ans * (r - l) % mod
	r = l
if l:
	ans = 0
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 998244353
indexOf = {}
for i in range(n):
	indexOf[a[i]] = i
for elem in b:
	if elem not in indexOf:
		print(0)
		exit()
for i in range(m - 1):
	if indexOf[b[i]] > indexOf[b[i + 1]]:
		print(0)
		exit()
if min(a) < b[0]:
	print(0)
	exit()
for i in range(indexOf[b[-1]], n):
	if a[i] < b[-1]:
		print(0)
		exit()
ans = 1
for i in range(m - 1):
	possible = True
	x = indexOf[b[i]]
	y = indexOf[b[i + 1]]
	lastLower = x
	for index in range(x + 1, y):
		if a[index] < b[i]:
			possible = False
			break
		if a[index] < b[i + 1]:
			lastLower = index
	if not possible:
		print(0)
		exit()
	ans *= indexOf[b[i + 1]] - lastLower
	ans %= mod
print(ans)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def modInt(mod):

	class ModInt:

		def __init__(self, value):
			self.value = value % mod

		def __int__(self):
			return self.value

		def __eq__(self, other):
			return self.value == other.value

		def __hash__(self):
			return hash(self.value)

		def __add__(self, other):
			return ModInt(self.value + int(other))

		def __sub__(self, other):
			return ModInt(self.value - int(other))

		def __mul__(self, other):
			return ModInt(self.value * int(other))

		def __floordiv__(self, other):
			return ModInt(self.value // int(other))

		def __truediv__(self, other):
			return ModInt(self.value * pow(int(other), mod - 2, mod))

		def __pow__(self, exp):
			return pow(self.value, int(exp), mod)

		def __str__(self):
			return str(self.value)
	return ModInt

def main():
	ModInt = modInt(998244353)
	(n, m) = map(int, inputi().split())
	aa = [int(a) for a in inputi().split()]
	bb = [int(a) for a in inputi().split()]
	ap = n - 1
	bp = m - 1
	mn = 10000000000
	prod = ModInt(1)
	while ap >= 0 and bp >= 0:
		b = bb[bp]
		mn = min(mn, aa[ap])
		while mn > b and ap >= 0:
			ap -= 1
			mn = min(mn, aa[ap])
		if mn != b:
			print(0)
			return
		bpc = 0
		while mn == b and ap >= 0:
			bpc += 1
			ap -= 1
			mn = min(mn, aa[ap])
		if bp != 0:
			prod *= bpc
		bp -= 1
	if ap != -1 or bp != -1:
		print(0)
		return
	print(prod)
main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
(n, m) = sp()
a = l()[::-1]
b = l()[::-1]
a.append(0)
index = 0
mini = a[0]
while index < n and mini > b[0]:
	index += 1
	mini = min(mini, a[index])
if index == n or mini != b[0]:
	out(0)
	exit()
answer = 1
for i in range(m):
	if i == m - 1:
		if min(a[index:n]) != b[i]:
			out(0)
			exit()
		break
	r = True
	j = index
	while j < n and mini != b[i + 1]:
		j += 1
		mini = min(mini, a[j])
		if r and mini < b[i]:
			r = False
			answer = answer * (j - index) % mod2
	if j == n or mini != b[i + 1]:
		out(0)
		exit()
	i += 1
	index = j
out(answer)


from itertools import count
import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(left, right) = ({a[-1]: n - 1}, {a[-1]: n - 1})
	min_acc = [a[-1]] * n
	for i in range(n - 2, -1, -1):
		min_acc[i] = min(a[i], min_acc[i + 1])
		if min_acc[i] not in right:
			right[min_acc[i]] = i
		left[min_acc[i]] = i
	ans = 1
	mod = 998244353
	if min_acc[0] != b[0]:
		print(0)
		exit()
	for i in range(1, m):
		if b[i] not in left:
			print(0)
			exit()
		ans = ans * (right[b[i]] - left[b[i]] + 1) % mod
	print(ans)
main()


inp = lambda : map(int, input().split(' '))
(m, n) = inp()
arr1 = tuple(inp())
arr2 = tuple(inp())
ans = 1
i = m - 1
j = n - 1
while j >= 0 and ans:
	cnt = 0
	seen = 0
	if j == 0:
		if i >= 0 and min(arr1[0:i + 1]) == arr2[j]:
			cnt = 1
	else:
		while arr1[i] >= arr2[j] and i >= 0:
			if arr1[i] == arr2[j]:
				seen = 1
			if seen:
				cnt += 1
			i -= 1
	ans = ans * cnt % 998244353
	j -= 1
print(ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
M = [a[i] for i in range(n)]
for i in range(n - 2, -1, -1):
	M[i] = min(M[i], M[i + 1])
res = 1
mod = 998244353
val = b[m - 1]
id = n - 1
count = m - 1
(l, r) = (-1, -1)
while count and id > -1:
	if M[id] > val:
		id -= 1
	elif M[id] == val:
		if r == -1:
			r = id
		id -= 1
	elif val > M[id]:
		l = id + 1
		res *= max(r - l + 1, 0)
		res %= mod
		count -= 1
		r = -1
		l = -1
		val = b[count]
if count:
	res = 0
	print(res)
else:
	check = min((a[i] for i in range(id + 1)))
	if check == b[0]:
		print(res)
	else:
		print(0)


import sys
input = sys.stdin.readline
mod = 998244353
(N, M) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
bind = M - 1
defined = [-1] * M
ans = 1
for i in reversed(range(N)):
	a = A[i]
	if defined[bind] == -1:
		if B[bind] > a:
			ans = 0
			break
		elif B[bind] == a:
			defined[bind] = i
	elif B[bind] > a:
		if bind > 0 and B[bind - 1] <= a:
			ans = ans * (defined[bind] - i) % mod
			if B[bind - 1] == a:
				defined[bind - 1] = i
			bind -= 1
		else:
			ans = 0
			break
if bind != 0 or defined[bind] == -1:
	ans = 0
print(ans)


(n, m) = input().split()
n = int(n)
m = int(m)
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
MOD = 998244353
a.reverse()
b.reverse()

def Solve(a, b, n, m):
	if m > n:
		return 0
	men = a[0]
	pos = 0
	while pos < n and men > b[0]:
		pos += 1
		if pos >= n:
			break
		men = min(men, a[pos])
	if pos == n or men < b[0]:
		return 0
	result = 1
	count = 0
	while count != m - 1:
		newPos = pos
		mid = True
		while newPos < n and men != b[count + 1]:
			newPos += 1
			if newPos >= n:
				break
			men = min(men, a[newPos])
			if mid and a[newPos] < b[count]:
				mid = False
				result = result * (newPos - pos) % MOD
		if newPos == n or men != b[count + 1]:
			return 0
		count += 1
		pos = newPos
	for i in range(pos, n):
		if a[i] < men:
			men = a[i]
	if men == b[m - 1]:
		return result
	else:
		return 0
print(Solve(a, b, n, m))


import sys
from collections import deque, Counter
from itertools import product
from functools import reduce
input = sys.stdin.buffer.readline
MOD = 998244353
(n, m) = map(int, input().split())
a = list(map(int, reversed(input().split())))
b = list(map(int, reversed(input().split())))
if min(a) < b[-1]:
	print(0)
	exit()
cc = 1
(ap, bp, bc, ok) = (0, 0, 0, 0)
while ap < n:
	(av, bv) = (a[ap], b[bp])
	if av >= bv:
		if av == bv:
			ok = 1
		bc += ok
		ap += 1
	else:
		if not ok:
			break
		cc = cc * bc % MOD
		bp += 1
		(bc, ok) = (0, 0)
if not ok or bp != m - 1:
	cc = 0
print(cc)


import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
from bisect import bisect_right
from collections import deque
from math import gcd
mod = 998244353

def main():
	(a, b) = map(int, input().split())
	arr = list(map(int, input().split()))
	brr = list(map(int, input().split()))
	ind = [-1] * b
	last_ind = [-1] * b
	for (i, ele) in enumerate(arr):
		pos = bisect_right(brr, ele)
		if pos > 0 and brr[pos - 1] == ele:
			last_ind[pos - 1] = i
		if pos < b:
			ind[pos] = i
	bol = True if ind[0] == -1 else False
	for i in range(b):
		if last_ind[i] <= ind[i]:
			bol = False
	if bol:
		ans = 1
		for i in range(1, b):
			ans = ans * (last_ind[i] - ind[i]) % mod
		print(ans)
	else:
		print(0)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, m) = map(int, input().split())
a = list(map(int, reversed(input().split())))
b = list(map(int, reversed(input().split())))
if min(a) < b[-1]:
	print(0)
	exit()
cc = 1
(ap, bp, bc, ok) = (0, 0, 0, 0)
while ap < n:
	(av, bv) = (a[ap], b[bp])
	if av >= bv:
		if av == bv:
			ok = 1
		bc += ok
		ap += 1
	else:
		if not ok:
			break
		cc = cc * bc % 998244353
		bp += 1
		(bc, ok) = (0, 0)
if not ok or bp != m - 1:
	cc = 0
print(cc)


import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List

def solve(N, M, A, B):
	if min(A) < B[0]:
		return 0
	lastindex = collections.defaultdict(int)
	for (i, v) in enumerate(A):
		lastindex[v] = max(lastindex[v], i)
	for v in B:
		if v not in lastindex:
			return 0
	for i in range(M - 1):
		(a, b) = (B[i], B[i + 1])
		if lastindex[a] > lastindex[b]:
			return 0
	firstindex = collections.defaultdict(int)
	for v in B:
		for i in range(lastindex[v], -1, -1):
			if A[i] < v:
				firstindex[v] = i + 1
				break
	if firstindex[B[0]] != 0:
		return 0
	MOD = 998244353
	rightmin = [10 ** 9 + 100]
	for v in reversed(A):
		rightmin.append(min(rightmin[-1], v))
	rightmin = rightmin[::-1]
	for v in B[1:]:
		if rightmin[lastindex[v]] < v:
			return 0
	ans = 1
	for v in B[1:]:
		ans *= lastindex[v] - firstindex[v] + 1
		ans %= MOD
	return ans
(N, M) = map(int, input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
print(solve(N, M, A, B))


mod = 998244353

def solve(a, b):
	j = len(a) - 1
	pos = 1
	for i in reversed(range(1, len(b))):
		while j >= 0 and a[j] != b[i]:
			if a[j] < b[i]:
				return 0
			j -= 1
		if j < 0:
			return 0
		x = j
		small = None
		y = None
		while j >= 0 and a[j] >= b[i]:
			j -= 1
			if a[j] < b[i - 1]:
				return 0
			if a[j] == b[i - 1]:
				y = j
		small = j
		while j >= 0 and y is None:
			j -= 1
			if a[j] < b[i - 1]:
				return 0
			if a[j] == b[i - 1]:
				y = j
		if y is None:
			return 0
		pos *= (x - small) % mod
	x = None
	while j >= 0:
		if a[j] < b[0]:
			return 0
		if a[j] == b[0]:
			x = j
		j -= 1
	if x is None:
		return 0
	return pos % mod
input()
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(solve(a, b))


import os
import sys
from io import BytesIO, IOBase

def main():
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	a = a[::-1]
	b = b[::-1]
	ans = 1
	mod = 998244353
	i = 0
	for x in b:
		fs = n + 1
		j = i
		while j < len(a) and a[j] >= x:
			if a[j] == x:
				fs = min(fs, j)
			j += 1
		if fs == n + 1:
			print(0)
			exit(0)
		i = j
		if x == b[-1]:
			break
		ans *= i - fs
		ans %= mod
	if i != n:
		print(0)
		exit(0)
	print(ans % mod)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


mod = 998244353
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = []
d = {}
for (i, x) in enumerate(a):
	if x not in d:
		d[x] = []
	d[x].append(i)
	while len(s) > 0 and x <= a[s[-1]]:
		s.pop()
	s.append(i)
idx = []
(i, j) = (0, 0)
while j < len(s) and i < m:
	if a[s[j]] == b[i]:
		idx.append(j)
		i += 1
	j += 1
if a[s[0]] != b[0] or len(idx) < m:
	print(0)
else:
	ans = 1
	for i in range(1, m):
		p = idx[i]
		pre = a[s[p - 1]]
		ans = ans * (d[b[i]][-1] - d[pre][-1]) % mod
	print(ans)


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = list(map(int, list(next_line)))
		elif input_format == 5:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c

def mapl(iterable, format=0):
	if format == 0:
		return list(map(int, iterable))
	elif format == 1:
		return list(map(str, iterable))
	elif format == 2:
		return list(map(list, iterable))

def solve():
	mod = 998244353
	(n, m) = input(1)
	a = input(1)
	b = input(1)
	pa = n - 1
	f = []
	c = 1
	for pb in range(m - 1, -1, -1):
		if pa < 0:
			out(0)
			return
		while a[pa] > b[pb]:
			pa -= 1
			if pa < 0:
				out(0)
				return
		log(pb, pa)
		if a[pa] != b[pb]:
			out(0)
			return
		pa -= 1
		if pa >= 0:
			log('a', a[pa], b[pb], pa)
			while a[pa] >= b[pb]:
				c += 1
				pa -= 1
				if pa < 0:
					c = 1
					break
		f.append(c)
		c = 1
	log('p', pa)
	if pa >= 0:
		out(0)
		return
	log(f)
	t = 1
	for i in f:
		t *= i
		t %= mod
	out(t)
	return
solve()


import sys
import math
import collections

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_split_input():
	return list(map(int, input().split()))
t = 1
for ti in range(1, t + 1):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	MOD = 998244353
	out = 1
	first = -1
	curr = m - 1
	for i in range(n - 1, -1, -1):
		while a[i] < b[curr]:
			if first > -1:
				out *= first - i
				out %= MOD
			else:
				out = 0
			first = -1
			curr -= 1
			if curr < 0:
				out = 0
				break
		if a[i] == b[curr] and first == -1:
			first = i
	if curr == 0 and first != -1:
		print(out)
	else:
		print(0)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 998244353
a = a[::-1]
b = b[::-1]
(i, j) = (0, 0)
ans = 1
while ans and j < m:
	cnt = 0
	while i < n and a[i] >= b[j]:
		if cnt:
			cnt += 1
		elif a[i] == b[j]:
			cnt = 1
		i += 1
	if j == m - 1:
		cnt = min(cnt, 1)
		if i <= n - 1:
			cnt = 0
	ans = ans * cnt % mod
	j += 1
print(ans)


(n, m) = map(int, input().split())
ai = list(map(int, input().split()))
maxn = 10 ** 9 + 1
bi = list(map(int, input().split())) + [maxn]
mod = 998244353
bi2 = [0] * m
bi3 = [0] * m
j = m - 1
temp = 0
for i in range(n - 1, -1, -1):
	if ai[i] == bi[j]:
		temp = 1
		bi2[j] = i
		j -= 1
		if j == -1:
			break
		continue
	elif ai[i] < bi[j]:
		j = -2
		break
	if ai[i] >= bi[j + 1] and temp == 1:
		bi3[j] += 1
	else:
		temp = 0
if j != -1 or min(bi) > min(ai):
	print(0)
else:
	ans = 1
	for i in range(m - 1):
		ans *= bi3[i] + 1
		ans %= mod
	print(ans)


def getint():
	return int(input())

def getint2():
	return map(int, input().split())

def getintlist():
	return map(int, input().split())

def getstring():
	return input()
(n, m) = getint2()
a = list(getintlist())
b = list(getintlist())
for i in range(n - 2, -1, -1):
	if a[i] > a[i + 1]:
		a[i] = a[i + 1]
ans = 1
mod = 998244353
if a[0] != b[0]:
	print(0)
else:
	(r, ans, l) = (n, 1, 0)
	for b in b[::-1]:
		while r - 1 >= 0 and a[r - 1] > b:
			r -= 1
		if r == 0 or a[r - 1] != b:
			ans = 0
			break
		l = r - 1
		while l - 1 >= 0 and a[l - 1] == b:
			l -= 1
		if l:
			ans = ans * (r - l) % mod
		r = l
	if l:
		ans = 0
	print(ans)


import sys
import math
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
last = dict()
for i in range(n):
	last[a[i]] = i
prev = [0] * n
stack = []
for i in range(n):
	while len(stack) > 0 and a[stack[-1]] >= a[i]:
		stack.pop()
	prev[i] = -1 if len(stack) == 0 else stack[-1]
	stack.append(i)
suf = [0] * n
minVal = a[-1]
for i in range(n - 1, -1, -1):
	minVal = min(minVal, a[i])
	suf[i] = minVal
mod = 998244353
ans = 1 if min(a) == b[0] else 0
for i in b:
	idx = last.get(i, -1)
	if idx == -1 or a[idx] > suf[idx]:
		ans = 0
	if i > b[0]:
		ans = ans * (idx - prev[idx])
	ans = ans % mod
print(ans)


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
MOD = 998244353

def solve(n, m, a, b):
	a.reverse()
	b.reverse()
	ad = {}
	for i in range(n):
		if a[i] not in ad:
			ad[a[i]] = []
		ad[a[i]].append(i)
	cnt = 1
	if b[0] not in ad:
		return 0
	x = ad[b[0]][0]
	min_ax = min(a[:x + 1])
	if min_ax < b[0]:
		return 0
	for i in range(1, m):
		if b[i] not in ad:
			return 0
		k = 0
		yy = ad[b[i]]
		while k < len(yy) and yy[k] < x:
			k += 1
		if k > len(yy) - 1:
			return 0
		y = yy[k]
		min_xy = min(a[x:y + 1])
		if min_xy < b[i]:
			return 0
		mid = x + 1
		while mid <= y and a[mid] >= b[i - 1]:
			mid += 1
		cnt = cnt * (mid - x) % MOD
		x = y
	min_last = min(a[x:])
	if min_last < b[m - 1]:
		return 0
	return cnt

def main():
	(n, m) = ria()
	a = ria()
	b = ria()
	wi(solve(n, m, a, b))
main()


import sys
import math
from collections import defaultdict, deque
import heapq
mod = 998244353
(n, m) = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
i = n - 1
ind = m - 1
add = 1
put = 0
z = True
minn = b[0]
boolb = [False for _ in range(m)]
while i >= 0:
	if a[i] > b[ind]:
		if b[ind] != minn:
			add += put
		add %= mod
		i -= 1
		continue
	if a[i] == b[ind]:
		boolb[ind] = True
		if z:
			put = add
			z = False
			add = 0
			add += put
			i -= 1
			continue
		if b[ind] != minn:
			add += put
		i -= 1
		add %= mod
		continue
	if a[i] < b[ind]:
		ind -= 1
		if ind < 0:
			print(0)
			sys.exit()
		if a[i] < b[ind]:
			print(0)
			sys.exit()
		z = True
		while i >= 0 and a[i] != b[ind]:
			i -= 1
		if i < 0:
			print(0)
			sys.exit()
a = True
for i in range(m):
	a = a and boolb[i]
if not a:
	print(0)
	sys.exit()
ans = add
ans %= mod
print(ans)


(n, m) = map(int, input().split())
lstn = list(map(int, input().split()))
b = list(map(int, input().split()))
hr = [0 for i in range(m)]
hhr = [-1 for i in range(m)]
hhl = [-1 for i in range(m)]

def bnp(lst, elem, pos):
	l = -1
	r = len(lst)
	while r - l > 1:
		h = (r + l) // 2
		if lst[h] > elem:
			r = h
		else:
			l = h
	if l == -1:
		print(0)
		exit()
	if lst[l] == elem:
		hr[l] = 1
		hhr[l] = pos
	if l != len(hhl) - 1:
		hhl[l + 1] = pos + 1
	return l
mod = 998244353
bnpp = [bnp(b, lstn[i], i) for i in range(n)]
num = 0
if sum(hr) != m:
	print(0)
	exit()
ans = 1
for i in range(1, m):
	if hhr[i] - hhl[i] + 1 <= 0:
		print(0)
		exit()
	ans *= hhr[i] - hhl[i] + 1
	ans %= mod
print(ans)


import os, sys
from io import BytesIO, IOBase

def main():
	mod = 998244353
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	dct = {}
	if n == m:
		if a != b:
			print(0)
		else:
			print(1)
		return
	for (ind, i) in enumerate(a):
		dct[i] = ind
	for i in b:
		if dct.get(i) == None:
			print(0)
			return
	x = dct[b[0]]
	if min(a[:x + 1]) != b[0]:
		print(0)
		return
	ans = 1
	for i in range(1, m):
		y = dct[b[i]]
		xx = [a[y]]
		for r in range(y - 1, x, -1):
			xx.append(min(xx[-1], a[r]))
		(mini, val) = (10 ** 10, 0)
		for j in range(x, y):
			mini = min(mini, a[j])
			if mini == b[i - 1] and xx[-1 - j + x] == b[i]:
				val += 1
		(ans, x) = (ans * val % mod, y)
	if min(a[x:]) != b[-1]:
		print(0)
		return
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()