We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times.

On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \ldots, a_n$ to the left in order to fill in the empty space.

You are given the initial permutation $a_1, a_2, \ldots, a_n$ and the resulting array $b_1, b_2, \ldots, b_k$. All elements of an array $b$ are distinct. Calculate the number of possible sequences of indices $t_1, t_2, \ldots, t_k$ modulo $998\,244\,353$.


-----Input-----

Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100\,000$), denoting the number of test cases, followed by a description of the test cases.

The first line of each test case contains two integers $n, k$ ($1 \le k < n \le 200\,000$): sizes of arrays $a$ and $b$.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): elements of $a$. All elements of $a$ are distinct.

The third line of each test case contains $k$ integers $b_1, b_2, \ldots, b_k$ ($1 \le b_i \le n$): elements of $b$. All elements of $b$ are distinct.

The sum of all $n$ among all test cases is guaranteed to not exceed $200\,000$.


-----Output-----

For each test case print one integer: the number of possible sequences modulo $998\,244\,353$.


-----Example-----
Input
3
5 3
1 2 3 4 5
3 2 5
4 3
4 3 2 1
4 3 1
7 4
1 4 7 3 6 2 5
3 2 4 5

Output
2
0
4



-----Note-----

$\require{cancel}$

Let's denote as $a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$ an operation over an element with index $i$: removal of element $a_i$ from array $a$ and appending element $a_{i+1}$ to array $b$.

In the first example test, the following two options can be used to produce the given array $b$:  $1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$; $(t_1, t_2, t_3) = (4, 3, 2)$;  $1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$; $(t_1, t_2, t_3) = (4, 1, 2)$. 

In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $4$, namely number $3$, which means that it couldn't be added to array $b$ on the second step.

In the third example test, there are four options to achieve the given array $b$:  $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$; $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$;

Difficulty: MEDIUM_HARD
Tags: Combinatorics

Implementation

Greedy algorithms

Spanning trees

Data structures
Skill types: Data structures

Greedy algorithms

Starter code:

Solutions:
q = 998244353
ans = []
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	pos = {a: i for (i, a) in enumerate(A, 1)}
	u = {i: 0 for i in range(1, n + 1)}
	for b in B:
		u[pos[b]] = 1
	u[0] = u[n + 1] = 1
	cnt = 0
	for b in B:
		cur = 2 - u[pos[b] - 1] - u[pos[b] + 1]
		if not cur:
			ans.append(0)
			break
		elif cur == 2:
			cnt += 1
		u[pos[b]] = 0
	else:
		ans.append(pow(2, cnt, q))
print(*ans, sep='\n')


from collections import defaultdict
import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	a = [int(i) for i in input().split() if i != '\n']
	b = [int(i) for i in input().split() if i != '\n']
	ind = [-1] * n
	ans = 1
	for i in range(len(b)):
		ind[b[i] - 1] = i
	for i in range(n):
		tmp = 0
		if ind[a[i] - 1] == -1:
			continue
		if i > 0 and ind[a[i - 1] - 1] < ind[a[i] - 1]:
			tmp += 1
		if i < n - 1 and ind[a[i + 1] - 1] < ind[a[i] - 1]:
			tmp += 1
		ans *= tmp
		ans %= 998244353
	print(ans)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	mod = 998244353
	(n, k) = R()
	a = L()
	b = L()
	v = [0] * (n + 2)
	ind = [0] * (n + 1)
	for i in range(n):
		ind[a[i]] = i + 1
		v[i + 1] = 1
	for i in range(k):
		v[ind[b[i]]] = 0
	ans = 1
	for i in range(k):
		p = ind[b[i]]
		ans *= v[p - 1] + v[p + 1]
		ans %= mod
		v[p] = 1
	print(ans)


mxn = 998244353
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pre = [i - 1 for i in range(n)]
	next = [i + 1 for i in range(n)]
	vis = [0] * (n + 1)
	dct = [0] * (n + 1)
	for i in range(n):
		dct[a[i]] = i
	for num in b:
		vis[num] = 1
	res = 1
	case = 1
	for num in b:
		idx = dct[num]
		left = -1
		right = -1
		count = 0
		if pre[idx] >= 0:
			left = a[pre[idx]]
			if vis[left] == 0:
				count += 1
		if next[idx] < n:
			right = a[next[idx]]
			if vis[right] == 0:
				count += 1
		if not count:
			print(0)
			case = 0
			break
		else:
			res = res * count % mxn
			if left != -1 and vis[left] == 0:
				di = pre[idx]
			else:
				di = next[idx]
			if di:
				next[di - 1] = next[di]
			if di + 1 < n:
				pre[di + 1] = pre[di]
			vis[num] = 0
	if case:
		print(res)


from sys import stdin, stdout

def identify_the_operations(n, k, a_a, b_a):
	MOD = 998244353
	idx_a = [0] * (n + 1)
	bit_a = [0] * (n + 1)
	res = 1
	for i in range(n):
		idx_a[a_a[i]] = i
		bit_update(bit_a, i, 1)
	b_s = set(b_a)
	for b in b_a:
		b_s.remove(b)
		cv = bit_query(bit_a, idx_a[b])
		h = right_bs(idx_a[b] + 1, n - 1, cv, bit_a)
		l = left_bs(0, idx_a[b] - 1, cv, bit_a)
		if l != -1 and a_a[l] in b_s:
			l = -1
		if h != -1 and a_a[h] in b_s:
			h = -1
		mul = 0
		if h == -1 and l == -1:
			return 0
		elif h == -1:
			mul = 1
			bit_update(bit_a, l, -1)
		elif l == -1:
			mul = 1
			bit_update(bit_a, h, -1)
		else:
			mul = 2
			bit_update(bit_a, h, -1)
		res *= mul
		res %= MOD
	return res

def right_bs(l, h, cv, bit_a):
	if l > h or cv == bit_query(bit_a, h):
		return -1
	while l < h:
		m = (l + h) // 2
		if bit_query(bit_a, m) != cv:
			h = m
		else:
			l = m + 1
	return h

def left_bs(l, h, cv, bit_a):
	if l > h or cv == bit_query(bit_a, l):
		return -1
	while l < h:
		m = (l + h + 1) // 2
		if bit_query(bit_a, m) != cv:
			l = m
		else:
			h = m - 1
	return l

def bit_update(bit_a, i, delta):
	i += 1
	while i < len(bit_a):
		bit_a[i] += delta
		i += i & -i

def bit_query(bit_a, i):
	i += 1
	r = 0
	while i > 0:
		r += bit_a[i]
		i -= i & -i
	return r
t = int(stdin.readline())
for _ in range(t):
	(n, k) = map(int, stdin.readline().split())
	a_a = list(map(int, stdin.readline().split()))
	b_a = list(map(int, stdin.readline().split()))
	res = identify_the_operations(n, k, a_a, b_a)
	stdout.write(str(res) + '\n')


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	r = [0] * n
	for i in range(n):
		r[a[i] - 1] = i
	b = list(map(int, input().split()))
	d = [0] * n
	for i in range(k):
		d[b[i] - 1] = 1
	cnt = 0
	for i in range(k):
		idx = r[b[i] - 1]
		t = 0
		if idx > 0 and d[a[idx - 1] - 1] == 0:
			t += 1
		if idx < n - 1 and d[a[idx + 1] - 1] == 0:
			t += 1
		if t == 0:
			print(0)
			break
		elif t == 2:
			cnt += 1
		d[b[i] - 1] = 0
	else:
		print(pow(2, cnt, 998244353))


mod = 998244353
import sys

def input():
	return sys.stdin.readline()
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	X = [0] * n
	for i in range(n):
		X[A[i] - 1] = i
	Y = [-1] * n
	for i in range(k):
		Y[X[B[i] - 1]] = i
	ans = 1
	Y += [n]
	i = -1
	while i < n:
		if Y[i] == -1:
			i += 1
			continue
		j = i + 1
		x = 0
		while j <= n and Y[j] != -1:
			if x == 0:
				if Y[j] < Y[j - 1]:
					x += 1
			elif Y[j] > Y[j - 1]:
				ans = 0
				break
			j += 1
		if 0 <= i and j < n:
			ans *= 2
			ans %= mod
		i = j
	print(ans)


mod = 998244353
for _ in range(int(input())):
	(N, K) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	pos = {a: i for (i, a) in enumerate(A, 1)}
	seen = {i: 0 for i in range(1, N + 1)}
	for b in B:
		seen[pos[b]] = 1
	seen[0] = seen[N + 1] = 1
	ans = 1
	for b in B:
		ans = ans * (2 - seen[pos[b] - 1] - seen[pos[b] + 1]) % mod
		seen[pos[b]] = 0
	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()

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

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

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

def print_list(l):
	print(' '.join(map(str, l)))
from collections import defaultdict as dc
M = 998244353
for _ in range(N()):
	(n, k) = RL()
	a = RLL()
	b = RLL()
	dic = {}
	for i in range(n):
		dic[a[i]] = i
	used = set()
	count = dc(int)
	for t in b:
		i = dic[t]
		if i > 0 and a[i - 1] in used:
			count[a[i - 1]] += 1
		if i < n - 1 and a[i + 1] in used:
			count[a[i + 1]] += 1
		used.add(t)
	res = 1
	for t in b:
		if dic[t] == 0 or dic[t] == n - 1:
			res *= 1 - count[t]
		else:
			res *= 2 - count[t]
			res %= M
		if res == 0:
			break
	print(res)


import sys
input = sys.stdin.buffer.readline

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))
MOD = 998244353
allAns = []
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	mapp = dict()
	for i in range(n):
		mapp[a[i]] = i + 1
	a = list(range(1, n + 1))
	b = [mapp[x] for x in b]
	numberUsedLater = [False for _a in range(n + 1)]
	for x in b:
		numberUsedLater[x] = True
	ans = 1
	for x in b:
		numberUsedLater[x] = False
		m = 0
		if x + 1 <= n and numberUsedLater[x + 1] == False:
			m += 1
		if x - 1 >= 1 and numberUsedLater[x - 1] == False:
			m += 1
		ans *= m
		ans %= MOD
	allAns.append(ans)
multiLineArrayPrint(allAns)


tests = int(input())
for test in range(tests):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	q = [0] * n
	for i in range(n):
		q[a[i] - 1] = i
	for i in range(k):
		b[i] = q[b[i] - 1]
	q = [0] * n
	for i in range(k):
		q[b[i]] = i
	mod = 998244353
	res = 1
	for i in range(k):
		cur = 0
		if b[i] > 0 and q[b[i] - 1] <= i:
			cur += 1
		if b[i] < n - 1 and q[b[i] + 1] <= i:
			cur += 1
		if i == n - 2:
			cur = min(cur, 1)
		res = res * cur % mod
	print(res)


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
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')
mod = 998244353
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = dict()
	for (i, v) in enumerate(a):
		d[v] = i
	ck = [0] * n
	for i in b:
		ck[d[i]] = 1
	ans = 1
	for x in b:
		i = d[x]
		ct = 0
		if i + 1 < n and ck[i + 1] == 0:
			ct += 1
		if i - 1 >= 0 and ck[i - 1] == 0:
			ct += 1
		ck[i] = 0
		ans *= ct
		ans %= mod
	print(ans)


mod = 998244353
for _ in range(int(input())):
	(N, K) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	pos = {a: i for (i, a) in enumerate(A, 1)}
	seen = {i: 0 for i in range(1, N + 1)}
	for b in B:
		seen[pos[b]] = 1
	seen[0] = seen[N + 1] = 1
	cnt = 0
	for b in B:
		cur = 2 - seen[pos[b] - 1] - seen[pos[b] + 1]
		if not cur:
			print(0)
			break
		elif cur == 2:
			cnt += 1
		seen[pos[b]] = 0
	else:
		print(pow(2, cnt, mod))


import sys
import math

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

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

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

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	(n, k) = MI()
	ans = 1
	x = [0] * (n + 1)
	y = [0] * (n + 1)
	a = LI()
	b = LI()
	mod = 998244353
	boo = True
	for i in range(n):
		x[a[i]] = i
	for i in range(k):
		y[b[i]] = i
	for i in range(k):
		count = 0
		tot = 0
		if x[b[i]] - 1 >= 0:
			if y[a[x[b[i]] - 1]] > i:
				count += 1
			tot += 1
		if x[b[i]] + 1 < n:
			if y[a[x[b[i]] + 1]] > i:
				count += 1
			tot += 1
		if tot == count:
			boo = False
			break
		elif count == 0 and tot == 2:
			ans *= 2
			ans %= mod
	print(0 if not boo else ans)


import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 998244353

def solve():
	ret = 1
	(n, k) = map(int, input().split())
	l = list(map(lambda x: int(x) - 1, input().split()))
	left = [-1] * n
	right = [-1] * n
	for i in range(n - 1):
		left[l[i + 1]] = l[i]
		right[l[i]] = l[i + 1]
	useable = [1] * n
	b = list(map(lambda x: int(x) - 1, input().split()))
	for v in b:
		useable[v] = 0
	for v in b:
		useable[v] = 1
		if left[v] != -1:
			lposs = useable[left[v]]
		else:
			lposs = 0
		if right[v] != -1:
			rposs = useable[right[v]]
		else:
			rposs = 0
		s = lposs + rposs
		if s == 0:
			return 0
		elif s == 2:
			ret *= 2
			ret %= M
		if lposs:
			d = left[v]
		else:
			d = right[v]
		(l, r) = (left[d], right[d])
		if l != -1:
			right[l] = r
		if r != -1:
			left[r] = l
	return ret
t = int(input())
out = []
for _ in range(t):
	out.append(solve())
print('\n'.join(map(str, out)))


import sys, atexit, io
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	ind = [-1] * n
	for i in range(n):
		ind[a[i] - 1] = i
	fixed = [0] * n
	for i in range(m):
		fixed[ind[b[i] - 1]] = 1
	ans = 1
	mod = 998244353
	for i in range(m):
		curr = b[i] - 1
		temp = 0
		if ind[curr] > 0 and fixed[ind[curr] - 1] == 0:
			temp += 1
		if ind[curr] < n - 1 and fixed[ind[curr] + 1] == 0:
			temp += 1
		ans *= temp
		ans %= mod
		fixed[ind[curr]] = 0
	print(ans)


import sys
input = sys.stdin.buffer.readline
MOD = 998244353
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	inB = [False for _ in range(n + 1)]
	for x in b:
		inB[x] = True
	idxInA = [-1 for _ in range(n + 1)]
	for i in range(n):
		idxInA[a[i]] = i
	left = [None for _ in range(n + 1)]
	right = [None for _ in range(n + 1)]
	for i in range(1, n):
		left[i] = i - 1
	for i in range(n - 1):
		right[i] = i + 1
	ans = 1
	for x in b:
		aIdx = idxInA[x]
		beforeAfterIndexes = []
		if left[aIdx] != None and inB[a[left[aIdx]]] == False:
			beforeAfterIndexes.append(left[aIdx])
		if right[aIdx] != None and inB[a[right[aIdx]]] == False:
			beforeAfterIndexes.append(right[aIdx])
		if len(beforeAfterIndexes) == 0:
			ans = 0
			break
		else:
			i = beforeAfterIndexes[0]
			if left[i] != None:
				right[left[i]] = right[i]
			if right[i] != None:
				left[right[i]] = left[i]
		if len(beforeAfterIndexes) == 2:
			ans *= 2
			ans %= MOD
		inB[x] = False
	print(ans)


import sys
input = sys.stdin.readline

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

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

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

def invr():
	return map(int, input().split())
cnt = inp()
c = [0] * 200010
left = [0] * 200010
right = [0] * 200010
e = [0] * 200010
for j in range(0, cnt):
	(n, k) = invr()
	a = list(invr())
	b = list(invr())
	result = 1
	for i in range(0, n):
		c[a[i]] = i
		if i != 0:
			left[a[i]] = a[i - 1]
		if i != n - 1:
			right[a[i]] = a[i + 1]
	e[0] = 1
	e[n + 1] = 1
	for i in range(0, k):
		e[b[i]] = 1
	for i in range(0, k):
		tmp = 0
		if e[left[b[i]]] != 1:
			tmp += 1
		if e[right[b[i]]] != 1:
			tmp += 1
		if tmp == 0:
			result = 0
			break
		result *= tmp
		result %= 998244353
		if e[left[b[i]]] != 1:
			left[b[i]] = left[left[b[i]]]
			right[left[b[i]]] = b[i]
		if e[left[b[i]]] == 1 and e[right[b[i]]] != 1:
			right[b[i]] = right[right[b[i]]]
			left[right[b[i]]] = b[i]
		e[b[i]] = 0
	for i in range(0, n + 2):
		c[i] = 0
		left[i] = 0
		right[i] = 0
		e[i] = 0
	print(result)


import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	ind = [-1] * n
	for i in range(n):
		ind[a[i] - 1] = i
	fixed = [0] * n
	for i in range(m):
		fixed[ind[b[i] - 1]] = 1
	ans = 1
	mod = 998244353
	for i in range(m):
		curr = b[i] - 1
		temp = 0
		if ind[curr] > 0 and fixed[ind[curr] - 1] == 0:
			temp += 1
		if ind[curr] < n - 1 and fixed[ind[curr] + 1] == 0:
			temp += 1
		ans *= temp
		ans %= mod
		fixed[ind[curr]] = 0
	print(ans)


import sys
input = sys.stdin.readline
mod = 998244353
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	X = [-1] * (n + 1)
	for i in range(n):
		X[A[i]] = i
	for i in range(k):
		B[i] = X[B[i]]
	Y = [0] * n
	for b in B:
		Y[b] = 1
	Y.append(1)
	ANS = 0
	for b in B:
		if Y[b - 1] == 1 and Y[b + 1] == 1:
			print(0)
			break
		elif Y[b - 1] == 0 and Y[b + 1] == 0:
			ANS += 1
		Y[b] = 0
	else:
		print(pow(2, ANS, mod))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
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 ** 32, func=lambda a, b: min(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

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	rem = set(l)
	b = list(map(int, input().split()))
	if n == 1:
		print(0)
		continue
	ans = 1
	re = set(b)
	d = defaultdict(int)
	for i in range(n):
		d[l[i]] = i
	for i in range(k):
		t = 0
		ind = d[b[i]]
		if ind - 1 >= 0:
			if l[ind - 1] not in re:
				t += 1
		if ind + 1 < n:
			if l[ind + 1] not in re:
				t += 1
		re.remove(l[ind])
		ans *= t
		ans %= mod1
		if t == 0:
			break
	print(ans % mod1)


import sys
input = sys.stdin.readline
MOD = 998244353
(T,) = map(int, input().split())
for _ in range(T):
	(N, K) = map(int, input().split())
	R = 1
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	a2i = [0] * (N + 1)
	for i in range(N):
		a2i[A[i]] = i + 1
	f = 0
	C = [0] * (N + 1)
	for b in B[::-1]:
		i = a2i[b]
		if i == 1:
			if C[i + 1]:
				f = 1
				break
			C[i] = 1
			continue
		if i == N:
			if C[i - 1]:
				f = 1
				break
			C[i] = 1
			continue
		if C[i + 1] and C[i - 1]:
			f = 1
			break
		elif C[i + 1] or C[i - 1]:
			C[i] = 1
		else:
			R = R * 2 % MOD
			C[i] = 1
	if f:
		print(0)
	else:
		print(R)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil, sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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))
from types import GeneratorType

def iterative(f, stack=[]):

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

def inp():
	return sys.stdin.readline().rstrip('\r\n')

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

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

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

def power(x, y, p):
	y %= p - 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 998244353

def solve(case):
	(n, k) = sep()
	a = lis()
	b = lis()
	have = {}
	for i in range(k):
		have[b[i]] = 1
	pos = {}
	for i in range(n):
		pos[a[i]] = i
	if len(b) == 1 and len(a) < 3:
		if b[0] in a:
			print(1)
		else:
			print(0)
		return
	ans = 1
	for i in range(k):
		left = -1
		right = -1
		ind = pos[b[i]]
		del have[b[i]]
		if ind == 0:
			if a[ind + 1] in have:
				ans = 0
				break
		elif ind == n - 1:
			if a[ind - 1] in have:
				ans = 0
				break
		else:
			if a[ind - 1] in have and a[ind + 1] in have:
				ans = 0
				break
			if a[ind - 1] not in have and a[ind + 1] not in have:
				ans *= 2
		ans %= mod
	print(ans % mod)
testcase(int(inp()))


from sys import stdin
input = stdin.readline
MOD = 998244353
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	where = [0] * n
	for i in range(n):
		where[a[i] - 1] = i
	for i in range(k):
		b[i] = where[b[i] - 1]
	sp = [-1] * n
	for i in range(k):
		sp[b[i]] = i

	def solve(sp):
		res = [0] * k
		mx = n
		for i in reversed(range(0, n)):
			if sp[i] == -1:
				mx = -1
			else:
				res[sp[i]] = 1 if mx < sp[i] else 0
				mx = max(mx, sp[i])
		return res
	ans1 = solve(sp)
	sp.reverse()
	ans2 = solve(sp)
	ans = 1
	for i in range(k):
		ans *= ans1[i] + ans2[i]
		ans %= MOD
	print(ans)


T = int(input())
for _ in range(T):
	res = 1
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	m = {}
	for i in range(len(b)):
		m[b[i]] = i + 1
	for i in range(len(a)):
		if a[i] in m.keys():
			temp = 0
			if i > 0 and (a[i - 1] in m.keys() and m[a[i]] > m[a[i - 1]] or a[i - 1] not in m.keys()):
				temp += 1
			if i < n - 1 and (a[i + 1] in m.keys() and m[a[i]] > m[a[i + 1]] or a[i + 1] not in m.keys()):
				temp += 1
			res *= temp
	print(res % 998244353)


import sys
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	(al, bl) = (list(map(int, input().split())), list(map(int, input().split())))
	(am, bm) = (dict([]), set(bl))
	for i in range(n):
		left = 0 if i == 0 else al[i - 1]
		right = 0 if i == n - 1 else al[i + 1]
		am[al[i]] = (left, right)
	(cc, MOD) = (1, 998244353)
	for u in bl:
		(left, right) = am[u]
		lcc = (left > 0 and left not in bm) + (right > 0 and right not in bm)
		cc = cc * lcc % MOD
		if cc == 0:
			break
		am.pop(u)
		bm.remove(u)
		if left > 0:
			(l, r) = am[left]
			am[left] = (l, right)
		if right > 0:
			(l, r) = am[right]
			am[right] = (left, r)
	print(cc)


MOD = 998244353
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	pos = [0] * (n + 1)
	ind = [-1] * (n + 1)
	ans = 1
	for i in range(len(b)):
		pos[b[i]] = 1
	for i in range(len(a)):
		ind[a[i]] = i
	for i in range(len(b)):
		ptr = ind[b[i]]
		c = 0
		if ptr - 1 >= 0 and pos[a[ptr - 1]] == 0:
			c = (c + 1) % MOD
		if ptr + 1 < n and pos[a[ptr + 1]] == 0:
			c = (c + 1) % MOD
		pos[a[ptr]] = 0
		ans = ans * c % MOD
	print(ans)


import sys
input = sys.stdin.readline
mod = 998244353
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = {}
	used = set()
	tmp = set(b)
	for i in range(n):
		if a[i] not in tmp:
			used.add(a[i])
		pos[a[i]] = i
	ans = 1
	for val in b:
		i = pos[val]
		if i == 0:
			if a[i + 1] not in used:
				print(0)
				break
		elif i == n - 1:
			if a[i - 1] not in used:
				print(0)
				break
		elif a[i - 1] in used and a[i + 1] in used:
			ans *= 2
			ans %= mod
		elif a[i - 1] not in used and a[i + 1] not in used:
			print(0)
			break
		used.add(a[i])
	else:
		print(ans)


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
mod = 998244353
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s1 = defaultdict(set)
	s1[a[0]].add(a[1])
	s1[a[-1]].add(a[-2])
	for ii in range(1, n - 1):
		s1[a[ii]].add(a[ii - 1])
		s1[a[ii]].add(a[ii + 1])
	s2 = set(b)
	ans = 1
	for j in range(k):
		s2.remove(b[j])
		cur = 0
		r = 0
		for kk in s1[b[j]]:
			if kk not in s2:
				r = kk
				cur += 1
		if cur == 0:
			ans = 0
			break
		else:
			s1[b[j]].remove(r)
			for kk in s1[r]:
				if kk != b[j]:
					s1[b[j]].add(kk)
					s1[kk].add(b[j])
					s1[kk].remove(r)
					break
			if cur == 2:
				ans = ans * 2 % mod
	print(ans)


from sys import stdin
caso = int(stdin.readline().strip())
mod = 998244353
for cas in range(caso):
	(n, m) = map(int, stdin.readline().strip().split())
	s = list(map(int, stdin.readline().strip().split()))
	s1 = list(map(int, stdin.readline().strip().split()))
	vis = [True for i in range(n + 1)]
	pos = [-1 for i in range(n + 1)]
	for i in range(m):
		vis[s1[i]] = False
	for i in range(n):
		pos[s[i]] = i
	ans = 1
	for i in range(m):
		aux = 0
		if pos[s1[i]] > 0 and vis[s[pos[s1[i]] - 1]]:
			aux += 1
		if pos[s1[i]] < n - 1 and vis[s[pos[s1[i]] + 1]]:
			aux += 1
		vis[s1[i]] = True
		ans = ans * aux % mod
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = {i: e for (e, i) in enumerate(a)}
	S = set([b[i] for i in range(k)])
	res = 1
	mod = 998244353
	left = [i - 1 for i in range(n)]
	right = [i + 1 for i in range(n)]
	for i in range(k):
		idx = pos[b[i]]
		tmp = 0
		if left[idx] >= 0:
			right[left[idx]] = right[idx]
			if a[left[idx]] not in S:
				tmp += 1
		if right[idx] < n:
			left[right[idx]] = left[idx]
			if a[right[idx]] not in S:
				tmp += 1
		res *= tmp
		res %= mod
	print(res)


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf, gcd, floor
from itertools import permutations
from copy import deepcopy
from heapq import *

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

def main():
	mod = 998244353
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		ind = [0] * (n + 1)
		c = set(b)
		for (i, v) in enumerate(a):
			ind[v] = i
		ans = 1
		for i in b:
			z = ind[i]
			m = 0
			if z + 1 < n and a[z + 1] not in c:
				m += 1
			if z - 1 >= 0 and a[z - 1] not in c:
				m += 1
			ans = ans * m % mod
			c.discard(i)
			if ans == 0:
				break
		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()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.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 collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 998244353

def solve():
	ans = 1
	(N, K) = getInts()
	A = getInts()
	C = []
	for (i, a) in enumerate(A):
		C.append((a, i))
	C.sort()
	B = getInts()
	to_use = set(B)
	for b in B:
		ind = C[b - 1][1]
		ops = [ind + 1, ind - 1]
		tot = 0
		for op in ops:
			if op < 0 or op > N - 1:
				continue
			if A[op] not in to_use:
				tot += 1
		if not tot:
			return 0
		ans *= tot
		ans %= MOD
		to_use.remove(b)
	return ans
for _ in range(getInt()):
	print(solve())


t = int(input())
inv = [0] * (2 * 10 ** 5 + 5)
check = [True] * (2 * 10 ** 5 + 5)
for _ in range(t):
	(n, k) = map(int, input().split())
	p = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		check[i] = True
		inv[i + 1] = 0
	for (idx, val) in enumerate(p):
		inv[val] = idx
	for val in b:
		check[inv[val]] = False
	ans = 1
	mod = 998244353
	for val in b:
		curr = inv[val]
		pos = 0
		if curr + 1 < n and check[curr + 1]:
			pos += 1
		if curr - 1 >= 0 and check[curr - 1]:
			pos += 1
		ans = ans * pos % mod
		check[curr] = True
	print(ans)


import sys
input = sys.stdin.readline
MOD = 998244353

def main():
	(n, k) = map(int, input().split())
	alst = list(map(int, input().split()))
	blst = list(map(int, input().split()))
	ans = 1
	dic = {}
	for (i, a) in enumerate(alst, 1):
		dic[a] = i
	for i in range(k):
		blst[i] = dic[blst[i]] - 1
	tf = [True for _ in range(n)]
	ans = 1
	for b in blst[::-1]:
		if b == 0:
			if not tf[1]:
				print(0)
				return
		elif b == n - 1:
			if not tf[n - 2]:
				print(0)
				return
		else:
			cnt = int(tf[b + 1]) + int(tf[b - 1])
			if cnt == 2:
				ans *= 2
				ans %= MOD
			elif cnt == 0:
				print(0)
				return
		tf[b] = False
	print(ans)
for _ in range(int(input())):
	main()


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, K, A, B):
	MOD = 998244353
	indices = {x: i for (i, x) in enumerate(A)}
	choices = []
	need = set()
	for b in B[::-1]:
		i = indices[b]
		c = 0
		if i - 1 >= 0 and A[i - 1] not in need:
			c += 1
		if i + 1 < N and A[i + 1] not in need:
			c += 1
		need.add(b)
		choices.append(c)
	ans = 1
	for x in choices:
		ans *= x
		ans %= MOD
	return ans
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N, K) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	B = [int(x) for x in input().split()]
	ans = solve(N, K, A, B)
	print(ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

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))
from types import GeneratorType

def iterative(f, stack=[]):

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

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

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

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

class MergeFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		self.num_sets -= 1
		self.parent[a] = b
		self.size[b] += self.size[a]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

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

def solve():
	mod = 998244353
	(n, k) = sep()
	ar = [-1] + lis() + [-1]
	ar2 = lis()
	s = set(ar2)
	s.add(-1)
	ind = defaultdict(int)
	for i in range(1, n + 1):
		ind[ar[i]] = i
	ans = 1
	for i in range(k):
		s.remove(ar2[i])
		t = 2
		inde = ind[ar2[i]]
		if ar[inde + 1] in s:
			t -= 1
		if ar[inde - 1] in s:
			t -= 1
		ans *= t
		ans %= mod
	print(ans)
testcase(int(inp()))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	mod = 998244353
	sb = set(b)
	idx = [0] * (n + 1)
	for i in range(n):
		idx[a[i]] = i
	ans = 1
	for i in range(k):
		jj = idx[b[i]]
		cnt = 0
		if jj >= 1 and a[jj - 1] not in sb:
			cnt += 1
		if jj <= n - 2 and a[jj + 1] not in sb:
			cnt += 1
		ans *= cnt
		ans %= mod
		sb.remove(b[i])
	print(ans)


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)

def solve(arrA, arrB):
	mod = 998244353
	flag = [0] * len(arrA)
	d = collections.defaultdict(int)
	for (i, c) in enumerate(arrA):
		d[c] = i
	ans = 1
	for c in arrB[::-1]:
		k = d[c]
		sc = 0
		if k - 1 >= 0:
			sc += 1 - flag[k - 1]
		if k + 1 < len(arrA):
			sc += 1 - flag[k + 1]
		ans *= sc
		ans %= mod
		flag[k] = 1
	return ans
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arrA = list(map(int, input().split()))
	arrB = list(map(int, input().split()))
	print(solve(arrA, arrB))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
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 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
mod = 998244353
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s = set(b)
	el = dict()
	for i in range(n):
		el[a[i]] = i
	r = 1
	for i in range(k):
		e = el[b[i]]
		c = 0
		if e > 0:
			if a[e - 1] not in s:
				c += 1
		if e < n - 1:
			if a[e + 1] not in s:
				c += 1
		s.remove(b[i])
		r *= c
		r %= mod
	print(r)


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())
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 linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

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

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

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 smt:

	def __init__(self, l, r, arr):
		self.l = l
		self.r = r
		self.value = (1 << 31) - 1 if l < r else arr[l]
		mid = (l + r) // 2
		if l < r:
			self.left = smt(l, mid, arr)
			self.right = smt(mid + 1, r, arr)
			self.value &= self.left.value & self.right.value

	def setvalue(self, x, val):
		if self.l == self.r:
			self.value = val
			return
		mid = (self.l + self.r) // 2
		if x <= mid:
			self.left.setvalue(x, val)
		else:
			self.right.setvalue(x, val)
		self.value = self.left.value & self.right.value

	def ask(self, l, r):
		if l <= self.l and r >= self.r:
			return self.value
		val = (1 << 31) - 1
		mid = (self.l + self.r) // 2
		if l <= mid:
			val &= self.left.ask(l, r)
		if r > mid:
			val &= self.right.ask(l, r)
		return val

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 prime

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):
	res = []
	for (ch, g) in groupby(it):
		res.append((ch, len(list(g))))
	return res

def judge(i):
	return i not in s and i != -1
t = N()
for i in range(t):
	(n, k) = RL()
	a = RLL()
	b = RLL()
	mod = 998244353
	s = set(b)
	ans = 1
	left = [-1] * (n + 1)
	right = [-1] * (n + 1)
	for i in range(n):
		if i != 0:
			left[a[i]] = a[i - 1]
		if i != n - 1:
			right[a[i]] = a[i + 1]
	for i in range(k):
		if judge(left[b[i]]) and judge(right[b[i]]):
			ans = ans * 2 % mod
			tmp = left[left[b[i]]]
			left[b[i]] = tmp
			if tmp != -1:
				right[tmp] = b[i]
			s.remove(b[i])
		elif judge(left[b[i]]):
			tmp = left[left[b[i]]]
			left[b[i]] = tmp
			if tmp != -1:
				right[tmp] = b[i]
			s.remove(b[i])
		elif judge(right[b[i]]):
			tmp = right[right[b[i]]]
			right[b[i]] = tmp
			if tmp != -1:
				left[tmp] = b[i]
			s.remove(b[i])
		else:
			ans = 0
			break
	print(ans)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations, combinations

def data():
	return sys.stdin.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')
sys.setrecursionlimit(100000)
INF = float('inf')
mod = 998244353
for t in range(int(data())):
	(n, k) = mdata()
	a = mdata()
	b = mdata()
	s = set(b)
	v = [1] * n
	d = dd(int)
	ans = 1
	for i in range(n):
		d[a[i]] = i
	for i in b:
		k = 0
		if d[i] < n - 1 and a[d[i] + 1] not in s:
			k += 1
		if d[i] > 0 and a[d[i] - 1] not in s:
			k += 1
		ans = ans * k % mod
		s.remove(i)
	out(ans)


import sys
input = sys.stdin.readline
testcase = int(input())
mod = 998244353
for _ in range(testcase):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	dca = {a[i] - 1: i for i in range(n)}
	dcb = {b[i] - 1: i for i in range(k)}
	ls = [1 for i in range(n)]
	for i in range(k):
		ls[dca[b[i] - 1]] = 0
	ans = 1
	for i in range(k):
		tmp = 0
		ind = dca[b[i] - 1]
		if ind > 0:
			tmp += ls[ind - 1]
		if ind < n - 1:
			tmp += ls[ind + 1]
		ans *= tmp
		ans %= mod
		ls[ind] = 1
	print(ans)


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 998244353
T = int(input())
for _ in range(T):
	(N, K) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	mapping = [-100] * (N + 1)
	for (i, a) in enumerate(A, 1):
		mapping[a] = i
	B = [mapping[b] for b in B]
	Left = list(range(-1, N + 1))
	Right = list(range(1, N + 2 + 1))
	ToUse = [False] * (N + 1)
	for b in B:
		ToUse[b] = True
	ans = 0
	for b in B:
		l = Left[b]
		r = Right[b]
		t = (l != 0 and (not ToUse[l])) + (r != N + 1 and (not ToUse[r]))
		ans += t - 1
		if t == 0:
			print(0)
			break
		if l != 0 and (not ToUse[l]):
			ll = Left[l]
			Left[b] = ll
			Right[ll] = b
		elif r != N + 1 and (not ToUse[r]):
			rr = Right[r]
			Right[b] = rr
			Left[rr] = b
		ToUse[b] = False
	else:
		ans = pow(2, ans, mod)
		print(ans)


import sys
readline = sys.stdin.readline
T = int(readline())
MOD = 998244353
Ans = [None] * T
for qu in range(T):
	(N, K) = map(int, readline().split())
	A = [0] + list(map(int, readline().split())) + [0]
	B = list(map(int, readline().split()))
	C = [None] * (N + 1)
	for i in range(1, N + 1):
		C[A[i]] = i
	ans = 1
	for b in B[::-1]:
		bi = C[b]
		res = 0
		if A[bi - 1]:
			res += 1
		if A[bi + 1]:
			res += 1
		A[bi] = 0
		ans = ans * res % MOD
	Ans[qu] = ans
print('\n'.join(map(str, 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')
for s in range(int(input())):
	(n, k) = map(int, input().split())
	arra = list(map(int, input().split()))
	arrb = list(map(int, input().split()))
	dict1 = {}
	mod = 998244353
	for s in range(n):
		dict1[arra[s]] = s
	ans = 1
	enc = set(arrb)
	for s in range(k):
		count = 0
		ind = dict1[arrb[s]]
		if ind > 0 and (not arra[ind - 1] in enc):
			count += 1
		if ind < n - 1 and (not arra[ind + 1] in enc):
			count += 1
		enc.remove(arrb[s])
		ans *= count
		ans = ans % mod
	print(ans)


import sys
input = sys.stdin.readline
R = lambda : map(int, input().split())
mod = 998244353
(t,) = R()
for _ in [0] * t:
	(n, k) = R()
	a = tuple(R())
	b = tuple(R())
	vis = {i: 1 for i in range(n + 1)}
	vis[0] = vis[n + 1] = 0
	pos = {a: i for (i, a) in enumerate(a, 1)}
	ans = 0
	for i in b:
		vis[pos[i]] = 0
	for i in b:
		if vis[pos[i] - 1] == 0 and vis[pos[i] + 1] == 0:
			ans = -1
			break
		if vis[pos[i] - 1] == 1 and vis[pos[i] + 1] == 1:
			ans += 1
		vis[pos[i]] = 1
	if ans != -1:
		print(pow(2, ans, mod))
	else:
		print(0)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	ind = [-1] * n
	for i in range(n):
		ind[a[i] - 1] = i
	fixed = [0] * n
	for i in range(m):
		fixed[ind[b[i] - 1]] = 1
	ans = 1
	mod = 998244353
	for i in range(m):
		curr = b[i] - 1
		temp = 0
		if ind[curr] > 0 and fixed[ind[curr] - 1] == 0:
			temp += 1
		if ind[curr] < n - 1 and fixed[ind[curr] + 1] == 0:
			temp += 1
		ans *= temp
		ans %= mod
		fixed[ind[curr]] = 0
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
moc = []
moc.append(1)
m = 998244353
for i in range(100000):
	moc.append(moc[-1] * 2 % m)
for test in range(t):
	[n, k] = list(map(int, input().split(' ')))
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	aa = [i + 1 for i in range(n)]
	s = [0] * n
	conv = [0] * (n + 1)
	for i in range(n):
		conv[a[i]] = i + 1
	bb = []
	for i in range(k):
		bb.append(conv[b[i]])
	for i in range(k):
		s[bb[i] - 1] = 1
	e = 0
	mozne = True
	for i in range(k):
		if bb[i] == aa[0]:
			if s[aa[1] - 1] == 1:
				mozne = False
				break
			s[bb[i] - 1] = 0
		elif bb[i] == aa[n - 1]:
			if s[aa[n - 2] - 1] == 1:
				mozne = False
				break
			s[bb[i] - 1] = 0
		else:
			if s[bb[i] - 2] == 1 and s[bb[i]] == 1:
				mozne = False
				break
			elif s[bb[i] - 2] == 0 and s[bb[i]] == 0:
				e += 1
			s[bb[i] - 1] = 0
	if mozne:
		print(moc[e])
	else:
		print(0)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
M = 998244353
t = 1
while t <= T:
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	b = list(map(int, input().split()))
	dic = {}
	nextb = {}
	for i in range(n):
		dic[arr[i]] = i
	for i in range(k):
		nextb[b[i]] = i
	ans = 0
	for i in range(k):
		r = dic[b[i]]
		neigh = 0
		if r + 1 < n and arr[r + 1] not in nextb:
			neigh += 1
		if r > 0 and arr[r - 1] not in nextb:
			neigh += 1
		if neigh == 0:
			ans = -1
			break
		else:
			ans += neigh - 1
		del nextb[b[i]]
	if ans >= 0:
		print(pow(2, ans, M))
	else:
		print(0)
	t += 1


import sys
from sys import stdin
tt = int(stdin.readline())
mod = 998244353
for loop in range(tt):
	(n, k) = map(int, stdin.readline().split())
	a = list(map(int, stdin.readline().split()))
	b = list(map(int, stdin.readline().split()))
	l = [None] * (n + 1)
	r = [None] * (n + 1)
	use = [True] * (n + 1)
	for i in b:
		use[i] = False
	for i in range(n):
		if i != n - 1:
			l[a[i]] = a[i + 1]
		if i != 0:
			r[a[i]] = a[i - 1]
	ans = 1
	for i in range(k):
		now = 0
		if l[b[i]] != None and use[l[b[i]]]:
			now += 1
		if r[b[i]] != None and use[r[b[i]]]:
			now += 1
		ans *= now
		ans %= mod
		if l[b[i]] != None:
			r[l[b[i]]] = r[b[i]]
		if r[b[i]] != None:
			l[r[b[i]]] = l[b[i]]
	print(ans % mod)


import sys
input = sys.stdin.readline

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

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

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

def invr():
	return map(int, input().split())
t = inp()
for _ in range(t):
	(n, m) = invr()
	a = inara()
	b = inara()
	posA = [0] * (n + 1)
	posB = [0] * (n + 1)
	for i in range(n):
		posA[a[i]] = i + 1
	for i in range(m):
		posB[b[i]] = i + 1
	ans = 1
	mod = 998244353
	for i in range(m):
		x = b[i]
		if posA[x] == 1:
			y = a[1]
			if posB[y] > i + 1:
				ans = 0
		elif posA[x] == n:
			y = a[-2]
			if posB[y] > i + 1:
				ans = 0
		else:
			p = a[posA[x] - 2]
			q = a[posA[x]]
			if posB[p] > i + 1 and posB[q] > i + 1:
				ans = 0
			elif posB[p] <= i + 1 and posB[q] <= i + 1:
				ans += ans
		if ans >= mod:
			ans -= mod
	print(ans)


import sys
input = sys.stdin.readline
mod = 998244353

def HalfDead():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	index_of_a = [-1] * (n + 5)
	for i in range(n):
		index_of_a[a[i]] = i
	set_of_b = set(b)
	ans = 1
	for x in b:
		c = 0
		idx = index_of_a[x]
		if idx >= 1:
			if a[index_of_a[a[idx - 1]]] not in set_of_b:
				c += 1
		if idx <= n - 2:
			if a[index_of_a[a[idx + 1]]] not in set_of_b:
				c += 1
		ans *= c
		ans %= mod
		set_of_b.remove(x)
	print(ans)
for _ in range(int(input())):
	HalfDead()


import os
import sys
from bisect import bisect_right
from io import BytesIO, IOBase
from math import gcd, inf, sqrt, ceil

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

def sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def getFactorization(x):
	ret = Counter()
	while x != 1:
		ret[spf[x]] += 1
		x = x // spf[x]
	return ret

def printDivisors(n):
	i = 2
	z = [1, n]
	while i <= sqrt(n):
		if n % i == 0:
			if n / i == i:
				z.append(i)
			else:
				z.append(i)
				z.append(n // i)
		i = i + 1
	return z

def create(n, x, f):
	pq = len(bin(n)[2:])
	if f == 0:
		tt = min
	else:
		tt = max
	dp = [[inf] * n for _ in range(pq)]
	dp[0] = x
	for i in range(1, pq):
		for j in range(n - (1 << i) + 1):
			dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
	return dp

def enquiry(l, r, dp, f):
	if l > r:
		return inf if not f else -inf
	if f == 1:
		tt = max
	else:
		tt = min
	pq1 = len(bin(r - l + 1)[2:]) - 1
	return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	x = []
	for i in range(2, n + 1):
		if prime[i]:
			x.append(i)
	return x

def main():
	from collections import Counter
	mod = 998244353
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		a = [int(x) for x in input().split()]
		z = Counter()
		for i in range(n):
			z[a[i]] = i
		b = [int(x) for x in input().split()]
		an = 1
		c = b[:]
		b = Counter(b)
		for i in c:
			xx = 0
			if z[i] != 0:
				if b[a[z[i] - 1]] == 0:
					xx += 1
			if z[i] != n - 1:
				if b[a[z[i] + 1]] == 0:
					xx += 1
			b[i] -= 1
			an *= xx
			an %= mod
		print(an)
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()


import os, sys
from io import BytesIO, IOBase

class Node:

	def __init__(self, val, le=0, ri=0, lval=0, rval=0):
		self.val = val
		self.le = le
		self.ri = ri
		self.lval = lval
		self.rval = rval

	def __str__(self):
		return '{} {} {} {} {}'.format(self.val, self.le, self.ri, self.lval, self.rval)

def main():
	mod = 998244353
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		map_b = [0] * (n + 1)
		lst = [0] * (n + 1)
		for y1 in b:
			map_b[y1] += 1
		for i in range(n):
			if not map_b[a[i]]:
				a[i] = 0
		cou = 0
		lef = 0
		lst[0] = Node(0)
		for i in a:
			if not i:
				cou += 1
			else:
				lst[i] = Node(val=i, le=lef, lval=cou)
				lst[lef].ri = i
				lst[lef].rval = cou
				(cou, lef) = (0, i)
		lst[lef].rval = cou
		ans = 1
		for i in b:
			if not i or (not lst[i].lval and (not lst[i].rval)):
				ans = 0
				break
			ans = ans * ((lst[i].lval != 0) + (lst[i].rval != 0)) % mod
			lst[lst[i].le].ri = lst[i].ri
			lst[lst[i].ri].le = lst[i].le
			lst[lst[i].le].rval += lst[i].rval
			lst[lst[i].ri].lval += lst[i].lval
		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()


import io, os
from math import *
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 998244353
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a_ = list(map(int, input().split()))
	a = {x: i for (i, x) in enumerate(a_)}
	b_ = list(map(int, input().split()))
	b = [a[x] for x in b_]
	c = {x: i for (i, x) in enumerate(b)}
	poss = 1
	for (i, d) in enumerate(b):
		canleft = d > 0 and (d - 1 not in c or c[d - 1] < i)
		canright = d < n - 1 and (d + 1 not in c or c[d + 1] < i)
		poss = poss * (canleft + canright) % M
	print(poss)


from __future__ import print_function
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
	from collections.abc import Sequence, MutableSequence
except ImportError:
	from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 50331648:
	from itertools import imap as map
	from itertools import izip as zip
	try:
		from thread import get_ident
	except ImportError:
		from dummy_thread import get_ident
else:
	from functools import reduce
	try:
		from _thread import get_ident
	except ImportError:
		from _dummy_thread import get_ident

def recursive_repr(fillvalue='...'):

	def decorating_function(user_function):
		repr_running = set()

		@wraps(user_function)
		def wrapper(self):
			key = (id(self), get_ident())
			if key in repr_running:
				return fillvalue
			repr_running.add(key)
			try:
				result = user_function(self)
			finally:
				repr_running.discard(key)
			return result
		return wrapper
	return decorating_function

class SortedList(MutableSequence):
	DEFAULT_LOAD_FACTOR = 1000

	def __init__(self, iterable=None, key=None):
		assert key is None
		self._len = 0
		self._load = self.DEFAULT_LOAD_FACTOR
		self._lists = []
		self._maxes = []
		self._index = []
		self._offset = 0
		if iterable is not None:
			self._update(iterable)

	def __new__(cls, iterable=None, key=None):
		if key is None:
			return object.__new__(cls)
		elif cls is SortedList:
			return object.__new__(SortedKeyList)
		else:
			raise TypeError('inherit SortedKeyList for key argument')

	@property
	def key(self):
		return None

	def _reset(self, load):
		values = reduce(iadd, self._lists, [])
		self._clear()
		self._load = load
		self._update(values)

	def clear(self):
		self._len = 0
		del self._lists[:]
		del self._maxes[:]
		del self._index[:]
		self._offset = 0
	_clear = clear

	def add(self, value):
		_lists = self._lists
		_maxes = self._maxes
		if _maxes:
			pos = bisect_right(_maxes, value)
			if pos == len(_maxes):
				pos -= 1
				_lists[pos].append(value)
				_maxes[pos] = value
			else:
				insort(_lists[pos], value)
			self._expand(pos)
		else:
			_lists.append([value])
			_maxes.append(value)
		self._len += 1

	def _expand(self, pos):
		_load = self._load
		_lists = self._lists
		_index = self._index
		if len(_lists[pos]) > _load << 1:
			_maxes = self._maxes
			_lists_pos = _lists[pos]
			half = _lists_pos[_load:]
			del _lists_pos[_load:]
			_maxes[pos] = _lists_pos[-1]
			_lists.insert(pos + 1, half)
			_maxes.insert(pos + 1, half[-1])
			del _index[:]
		elif _index:
			child = self._offset + pos
			while child:
				_index[child] += 1
				child = child - 1 >> 1
			_index[0] += 1

	def update(self, iterable):
		_lists = self._lists
		_maxes = self._maxes
		values = sorted(iterable)
		if _maxes:
			if len(values) * 4 >= self._len:
				values.extend(chain.from_iterable(_lists))
				values.sort()
				self._clear()
			else:
				_add = self.add
				for val in values:
					_add(val)
				return
		_load = self._load
		_lists.extend((values[pos:pos + _load] for pos in range(0, len(values), _load)))
		_maxes.extend((sublist[-1] for sublist in _lists))
		self._len = len(values)
		del self._index[:]
	_update = update

	def __contains__(self, value):
		_maxes = self._maxes
		if not _maxes:
			return False
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return False
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		return _lists[pos][idx] == value

	def discard(self, value):
		_maxes = self._maxes
		if not _maxes:
			return
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		if _lists[pos][idx] == value:
			self._delete(pos, idx)

	def remove(self, value):
		_maxes = self._maxes
		if not _maxes:
			raise ValueError('{0!r} not in list'.format(value))
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			raise ValueError('{0!r} not in list'.format(value))
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		if _lists[pos][idx] == value:
			self._delete(pos, idx)
		else:
			raise ValueError('{0!r} not in list'.format(value))

	def _delete(self, pos, idx):
		_lists = self._lists
		_maxes = self._maxes
		_index = self._index
		_lists_pos = _lists[pos]
		del _lists_pos[idx]
		self._len -= 1
		len_lists_pos = len(_lists_pos)
		if len_lists_pos > self._load >> 1:
			_maxes[pos] = _lists_pos[-1]
			if _index:
				child = self._offset + pos
				while child > 0:
					_index[child] -= 1
					child = child - 1 >> 1
				_index[0] -= 1
		elif len(_lists) > 1:
			if not pos:
				pos += 1
			prev = pos - 1
			_lists[prev].extend(_lists[pos])
			_maxes[prev] = _lists[prev][-1]
			del _lists[pos]
			del _maxes[pos]
			del _index[:]
			self._expand(prev)
		elif len_lists_pos:
			_maxes[pos] = _lists_pos[-1]
		else:
			del _lists[pos]
			del _maxes[pos]
			del _index[:]

	def _loc(self, pos, idx):
		if not pos:
			return idx
		_index = self._index
		if not _index:
			self._build_index()
		total = 0
		pos += self._offset
		while pos:
			if not pos & 1:
				total += _index[pos - 1]
			pos = pos - 1 >> 1
		return total + idx

	def _pos(self, idx):
		if idx < 0:
			last_len = len(self._lists[-1])
			if -idx <= last_len:
				return (len(self._lists) - 1, last_len + idx)
			idx += self._len
			if idx < 0:
				raise IndexError('list index out of range')
		elif idx >= self._len:
			raise IndexError('list index out of range')
		if idx < len(self._lists[0]):
			return (0, idx)
		_index = self._index
		if not _index:
			self._build_index()
		pos = 0
		child = 1
		len_index = len(_index)
		while child < len_index:
			index_child = _index[child]
			if idx < index_child:
				pos = child
			else:
				idx -= index_child
				pos = child + 1
			child = (pos << 1) + 1
		return (pos - self._offset, idx)

	def _build_index(self):
		row0 = list(map(len, self._lists))
		if len(row0) == 1:
			self._index[:] = row0
			self._offset = 0
			return
		head = iter(row0)
		tail = iter(head)
		row1 = list(starmap(add, zip(head, tail)))
		if len(row0) & 1:
			row1.append(row0[-1])
		if len(row1) == 1:
			self._index[:] = row1 + row0
			self._offset = 1
			return
		size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
		row1.extend(repeat(0, size - len(row1)))
		tree = [row0, row1]
		while len(tree[-1]) > 1:
			head = iter(tree[-1])
			tail = iter(head)
			row = list(starmap(add, zip(head, tail)))
			tree.append(row)
		reduce(iadd, reversed(tree), self._index)
		self._offset = size * 2 - 1

	def __delitem__(self, index):
		if isinstance(index, slice):
			(start, stop, step) = index.indices(self._len)
			if step == 1 and start < stop:
				if start == 0 and stop == self._len:
					return self._clear()
				elif self._len <= 8 * (stop - start):
					values = self._getitem(slice(None, start))
					if stop < self._len:
						values += self._getitem(slice(stop, None))
					self._clear()
					return self._update(values)
			indices = range(start, stop, step)
			if step > 0:
				indices = reversed(indices)
			(_pos, _delete) = (self._pos, self._delete)
			for index in indices:
				(pos, idx) = _pos(index)
				_delete(pos, idx)
		else:
			(pos, idx) = self._pos(index)
			self._delete(pos, idx)

	def __getitem__(self, index):
		_lists = self._lists
		if isinstance(index, slice):
			(start, stop, step) = index.indices(self._len)
			if step == 1 and start < stop:
				if start == 0 and stop == self._len:
					return reduce(iadd, self._lists, [])
				(start_pos, start_idx) = self._pos(start)
				if stop == self._len:
					stop_pos = len(_lists) - 1
					stop_idx = len(_lists[stop_pos])
				else:
					(stop_pos, stop_idx) = self._pos(stop)
				if start_pos == stop_pos:
					return _lists[start_pos][start_idx:stop_idx]
				prefix = _lists[start_pos][start_idx:]
				middle = _lists[start_pos + 1:stop_pos]
				result = reduce(iadd, middle, prefix)
				result += _lists[stop_pos][:stop_idx]
				return result
			if step == -1 and start > stop:
				result = self._getitem(slice(stop + 1, start + 1))
				result.reverse()
				return result
			indices = range(start, stop, step)
			return list((self._getitem(index) for index in indices))
		else:
			if self._len:
				if index == 0:
					return _lists[0][0]
				elif index == -1:
					return _lists[-1][-1]
			else:
				raise IndexError('list index out of range')
			if 0 <= index < len(_lists[0]):
				return _lists[0][index]
			len_last = len(_lists[-1])
			if -len_last < index < 0:
				return _lists[-1][len_last + index]
			(pos, idx) = self._pos(index)
			return _lists[pos][idx]
	_getitem = __getitem__

	def __setitem__(self, index, value):
		message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
		raise NotImplementedError(message)

	def __iter__(self):
		return chain.from_iterable(self._lists)

	def __reversed__(self):
		return chain.from_iterable(map(reversed, reversed(self._lists)))

	def reverse(self):
		raise NotImplementedError('use ``reversed(sl)`` instead')

	def islice(self, start=None, stop=None, reverse=False):
		_len = self._len
		if not _len:
			return iter(())
		(start, stop, _) = slice(start, stop).indices(self._len)
		if start >= stop:
			return iter(())
		_pos = self._pos
		(min_pos, min_idx) = _pos(start)
		if stop == _len:
			max_pos = len(self._lists) - 1
			max_idx = len(self._lists[-1])
		else:
			(max_pos, max_idx) = _pos(stop)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

	def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
		_lists = self._lists
		if min_pos > max_pos:
			return iter(())
		if min_pos == max_pos:
			if reverse:
				indices = reversed(range(min_idx, max_idx))
				return map(_lists[min_pos].__getitem__, indices)
			indices = range(min_idx, max_idx)
			return map(_lists[min_pos].__getitem__, indices)
		next_pos = min_pos + 1
		if next_pos == max_pos:
			if reverse:
				min_indices = range(min_idx, len(_lists[min_pos]))
				max_indices = range(max_idx)
				return chain(map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)))
			min_indices = range(min_idx, len(_lists[min_pos]))
			max_indices = range(max_idx)
			return chain(map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices))
		if reverse:
			min_indices = range(min_idx, len(_lists[min_pos]))
			sublist_indices = range(next_pos, max_pos)
			sublists = map(_lists.__getitem__, reversed(sublist_indices))
			max_indices = range(max_idx)
			return chain(map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)))
		min_indices = range(min_idx, len(_lists[min_pos]))
		sublist_indices = range(next_pos, max_pos)
		sublists = map(_lists.__getitem__, sublist_indices)
		max_indices = range(max_idx)
		return chain(map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices))

	def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
		_maxes = self._maxes
		if not _maxes:
			return iter(())
		_lists = self._lists
		if minimum is None:
			min_pos = 0
			min_idx = 0
		elif inclusive[0]:
			min_pos = bisect_left(_maxes, minimum)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_left(_lists[min_pos], minimum)
		else:
			min_pos = bisect_right(_maxes, minimum)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_right(_lists[min_pos], minimum)
		if maximum is None:
			max_pos = len(_maxes) - 1
			max_idx = len(_lists[max_pos])
		elif inclusive[1]:
			max_pos = bisect_right(_maxes, maximum)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_lists[max_pos])
			else:
				max_idx = bisect_right(_lists[max_pos], maximum)
		else:
			max_pos = bisect_left(_maxes, maximum)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_lists[max_pos])
			else:
				max_idx = bisect_left(_lists[max_pos], maximum)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

	def __len__(self):
		return self._len

	def bisect_left(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return self._len
		idx = bisect_left(self._lists[pos], value)
		return self._loc(pos, idx)

	def bisect_right(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_right(_maxes, value)
		if pos == len(_maxes):
			return self._len
		idx = bisect_right(self._lists[pos], value)
		return self._loc(pos, idx)
	bisect = bisect_right
	_bisect_right = bisect_right

	def count(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos_left = bisect_left(_maxes, value)
		if pos_left == len(_maxes):
			return 0
		_lists = self._lists
		idx_left = bisect_left(_lists[pos_left], value)
		pos_right = bisect_right(_maxes, value)
		if pos_right == len(_maxes):
			return self._len - self._loc(pos_left, idx_left)
		idx_right = bisect_right(_lists[pos_right], value)
		if pos_left == pos_right:
			return idx_right - idx_left
		right = self._loc(pos_right, idx_right)
		left = self._loc(pos_left, idx_left)
		return right - left

	def copy(self):
		return self.__class__(self)
	__copy__ = copy

	def append(self, value):
		raise NotImplementedError('use ``sl.add(value)`` instead')

	def extend(self, values):
		raise NotImplementedError('use ``sl.update(values)`` instead')

	def insert(self, index, value):
		raise NotImplementedError('use ``sl.add(value)`` instead')

	def pop(self, index=-1):
		if not self._len:
			raise IndexError('pop index out of range')
		_lists = self._lists
		if index == 0:
			val = _lists[0][0]
			self._delete(0, 0)
			return val
		if index == -1:
			pos = len(_lists) - 1
			loc = len(_lists[pos]) - 1
			val = _lists[pos][loc]
			self._delete(pos, loc)
			return val
		if 0 <= index < len(_lists[0]):
			val = _lists[0][index]
			self._delete(0, index)
			return val
		len_last = len(_lists[-1])
		if -len_last < index < 0:
			pos = len(_lists) - 1
			loc = len_last + index
			val = _lists[pos][loc]
			self._delete(pos, loc)
			return val
		(pos, idx) = self._pos(index)
		val = _lists[pos][idx]
		self._delete(pos, idx)
		return val

	def index(self, value, start=None, stop=None):
		_len = self._len
		if not _len:
			raise ValueError('{0!r} is not in list'.format(value))
		if start is None:
			start = 0
		if start < 0:
			start += _len
		if start < 0:
			start = 0
		if stop is None:
			stop = _len
		if stop < 0:
			stop += _len
		if stop > _len:
			stop = _len
		if stop <= start:
			raise ValueError('{0!r} is not in list'.format(value))
		_maxes = self._maxes
		pos_left = bisect_left(_maxes, value)
		if pos_left == len(_maxes):
			raise ValueError('{0!r} is not in list'.format(value))
		_lists = self._lists
		idx_left = bisect_left(_lists[pos_left], value)
		if _lists[pos_left][idx_left] != value:
			raise ValueError('{0!r} is not in list'.format(value))
		stop -= 1
		left = self._loc(pos_left, idx_left)
		if start <= left:
			if left <= stop:
				return left
		else:
			right = self._bisect_right(value) - 1
			if start <= right:
				return start
		raise ValueError('{0!r} is not in list'.format(value))

	def __add__(self, other):
		values = reduce(iadd, self._lists, [])
		values.extend(other)
		return self.__class__(values)
	__radd__ = __add__

	def __iadd__(self, other):
		self._update(other)
		return self

	def __mul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		return self.__class__(values)
	__rmul__ = __mul__

	def __imul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		self._clear()
		self._update(values)
		return self

	def __make_cmp(seq_op, symbol, doc):

		def comparer(self, other):
			if not isinstance(other, Sequence):
				return NotImplemented
			self_len = self._len
			len_other = len(other)
			if self_len != len_other:
				if seq_op is eq:
					return False
				if seq_op is ne:
					return True
			for (alpha, beta) in zip(self, other):
				if alpha != beta:
					return seq_op(alpha, beta)
			return seq_op(self_len, len_other)
		seq_op_name = seq_op.__name__
		comparer.__name__ = '__{0}__'.format(seq_op_name)
		return comparer
	__eq__ = __make_cmp(eq, '==', 'equal to')
	__ne__ = __make_cmp(ne, '!=', 'not equal to')
	__lt__ = __make_cmp(lt, '<', 'less than')
	__gt__ = __make_cmp(gt, '>', 'greater than')
	__le__ = __make_cmp(le, '<=', 'less than or equal to')
	__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
	__make_cmp = staticmethod(__make_cmp)

	@recursive_repr()
	def __repr__(self):
		return '{0}({1!r})'.format(type(self).__name__, list(self))

	def _check(self):
		try:
			assert self._load >= 4
			assert len(self._maxes) == len(self._lists)
			assert self._len == sum((len(sublist) for sublist in self._lists))
			for sublist in self._lists:
				for pos in range(1, len(sublist)):
					assert sublist[pos - 1] <= sublist[pos]
			for pos in range(1, len(self._lists)):
				assert self._lists[pos - 1][-1] <= self._lists[pos][0]
			for pos in range(len(self._maxes)):
				assert self._maxes[pos] == self._lists[pos][-1]
			double = self._load << 1
			assert all((len(sublist) <= double for sublist in self._lists))
			half = self._load >> 1
			for pos in range(0, len(self._lists) - 1):
				assert len(self._lists[pos]) >= half
			if self._index:
				assert self._len == self._index[0]
				assert len(self._index) == self._offset + len(self._lists)
				for pos in range(len(self._lists)):
					leaf = self._index[self._offset + pos]
					assert leaf == len(self._lists[pos])
				for pos in range(self._offset):
					child = (pos << 1) + 1
					if child >= len(self._index):
						assert self._index[pos] == 0
					elif child + 1 == len(self._index):
						assert self._index[pos] == self._index[child]
					else:
						child_sum = self._index[child] + self._index[child + 1]
						assert child_sum == self._index[pos]
		except:
			import sys
			import traceback
			traceback.print_exc(file=sys.stdout)
			print('len', self._len)
			print('load', self._load)
			print('offset', self._offset)
			print('len_index', len(self._index))
			print('index', self._index)
			print('len_maxes', len(self._maxes))
			print('maxes', self._maxes)
			print('len_lists', len(self._lists))
			print('lists', self._lists)
			raise

def identity(value):
	return value
import sys
input = sys.stdin.buffer.readline

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))
MOD = 998244353

class OrderedList(SortedList):

	def __init__(self, arg):
		super().__init__(arg)

	def rangeCountByValue(self, leftVal, rightVal):
		leftCummulative = self.bisect_left(leftVal)
		rightCummulative = self.bisect_left(rightVal + 1)
		return rightCummulative - leftCummulative
allAns = []
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	mapp = dict()
	for i in range(n):
		mapp[a[i]] = i + 1
	a = OrderedList(range(1, n + 1))
	b = [mapp[x] for x in b]
	numberUsedLater = [False for _a in range(n + 1)]
	for x in b:
		numberUsedLater[x] = True
	ans = 1
	for x in b:
		numberUsedLater[x] = False
		idx = a.index(x)
		m = 0
		sideNumberRemoved = False
		if idx + 1 < len(a):
			nextNo = a[idx + 1]
			if numberUsedLater[nextNo] == False:
				m += 1
				a.pop(idx + 1)
				sideNumberRemoved = True
		if idx - 1 >= 0:
			prevNo = a[idx - 1]
			if numberUsedLater[prevNo] == False:
				m += 1
				if sideNumberRemoved == False:
					a.pop(idx - 1)
					sideNumberRemoved = True
		ans *= m
		ans %= MOD
	allAns.append(ans)
multiLineArrayPrint(allAns)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = dict()
	for i in b:
		d[i] = -1
	ans = 1
	ck = set()
	ck.add(-1)
	ck.add(n)
	for (i, v) in enumerate(a):
		if v in d:
			d[v] = i
			ck.add(i)
	ans = 1
	for i in b:
		if d[i] + 1 in ck and d[i] - 1 in ck:
			ans = 0
			break
		if d[i] + 1 not in ck and d[i] - 1 not in ck:
			ans *= 2
		ck.remove(d[i])
		ans = ans % 998244353
	print(ans)


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

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

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

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

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

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
md = 998244353
for _ in range(II()):
	(n, k) = MI()
	aa = LI()
	bb = LI()
	atoi = [0] * (n + 1)
	for (i, a) in enumerate(aa):
		atoi[a] = i
	fin = [0] * (n + 2)
	fin[n] = fin[n + 1] = 1
	ans = 1
	for b in bb[::-1]:
		i = atoi[b]
		ans *= 2 - fin[i - 1] - fin[i + 1]
		ans %= md
		fin[i] = 1
	print(ans)


import sys, io, os
Z = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
Y = lambda : [*map(int, Z().split())]
M = 998244353
N = 200001
A = [0] * (2 * N)
B = [0] * N
o = []
for _ in range(int(Z())):
	(n, k) = Y()
	a = Y()
	b = Y()
	c = 1
	for i in range(n):
		B[i + 1] = 0
	for i in b:
		B[i] = 1
	for i in range(n):
		A[2 * a[i]] = a[i - 1] if i else -1
		A[2 * a[i] + 1] = a[i + 1] if i < n - 1 else -1
	for i in b:
		l = 2
		r = 0
		if A[2 * i] < 0 or B[A[2 * i]]:
			l -= 1
			r = 1
		if A[2 * i + 1] < 0 or B[A[2 * i + 1]]:
			l -= 1
		if l:
			c = c * l % M
		else:
			c = 0
			break
		B[i] = 0
		v = A[2 * A[2 * i + r] + r]
		if v > 0:
			A[2 * v + 1 - r] = i
		A[2 * i + r] = v
	o.append(str(c))
print('\n'.join(o))


import sys
input = sys.stdin.readline
t = int(input())
mod = 998244353
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a_index = [-1] * (n + 2)
	for i in range(n):
		a_index[a[i]] = i
	set_b = set(b)
	ans = 1
	for x in b:
		count = 0
		index = a_index[x]
		if index >= 1:
			if a[a_index[a[index - 1]]] not in set_b:
				count += 1
		if index <= n - 2:
			if a[a_index[a[index + 1]]] not in set_b:
				count += 1
		ans *= count
		ans %= mod
		set_b.remove(x)
	print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		bLoc = [-1] * n
		MOD = 998244353
		for i in range(len(b)):
			bLoc[b[i] - 1] = i
		ans = 1
		for i in range(n):
			case = 0
			if bLoc[a[i] - 1] == -1:
				continue
			if i > 0 and bLoc[a[i - 1] - 1] < bLoc[a[i] - 1]:
				case += 1
			if i < n - 1 and bLoc[a[i + 1] - 1] < bLoc[a[i] - 1]:
				case += 1
			ans *= case
			ans %= MOD
		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()


import sys
input = sys.stdin.readline
mod = 998244353
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	A = [0] + A + [n + 1]
	vis = [0 for i in range(n + 2)]
	vis[0] = 1
	vis[n + 1] = 1
	for i in B:
		vis[i] = 1
	G = {}
	for i in range(n + 2):
		G[A[i]] = i
	ans = 1
	for i in range(k):
		ind = G[B[i]]
		if vis[A[ind - 1]] == 1 and vis[A[ind + 1]] == 1:
			ans = 0
			break
		elif vis[A[ind - 1]] == 0 and vis[A[ind + 1]] == 0:
			ans = ans * 2 % mod
		vis[A[ind]] = 0
	print(ans)


import sys

def main():
	tokens = sys.stdin.read().split()
	curr = 1
	for _ in range(0, int(tokens[0])):
		(n, k) = (int(tokens[curr]), int(tokens[curr + 1]))
		a = [int(x) for x in tokens[curr + 2:curr + n + 2]]
		b = [int(x) for x in tokens[curr + n + 2:curr + n + 2 + k]]
		curr += n + k + 2
		o = [0] * (n + 1)
		mod = 998244353
		ans = 1
		for i in range(0, k):
			o[b[i]] = i + 1
		for i in range(0, n):
			if o[a[i]]:
				cnt = 0
				cnt += i > 0 and o[a[i - 1]] < o[a[i]]
				cnt += i < n - 1 and o[a[i + 1]] < o[a[i]]
				ans *= cnt
				ans %= mod
		print(ans)
main()


import sys
input = sys.stdin.readline
from collections import defaultdict
mod = 998244353
INF = float('inf')

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

def main():
	T = int(input())
	for _ in range(T):
		(N, K) = getlist()
		if N == 1:
			print(1)
		else:
			A = getlist()
			B = getlist()
			D = defaultdict(int)
			Drev = defaultdict(int)
			lis = [-1] * N
			for i in range(N):
				D[A[i] - 1] = i
			for i in range(K):
				itr = D[B[i] - 1]
				lis[itr] = 1
			ans = 1
			for i in range(K):
				itr = D[B[i] - 1]
				if itr == 0:
					if lis[itr + 1] == 1:
						ans = 0
				elif itr == N - 1:
					if lis[itr - 1] == 1:
						ans = 0
				else:
					cnt = 0
					if lis[itr - 1] == -1:
						cnt += 1
					if lis[itr + 1] == -1:
						cnt += 1
					ans *= cnt
					ans %= mod
					lis[itr] = -1
			print(ans)
main()


t = int(input())
from sys import stdin
from collections import defaultdict
for _ in range(t):
	(n, k) = [int(x) for x in stdin.readline().split()]
	l = [int(x) for x in stdin.readline().split()]
	p = [int(x) for x in stdin.readline().split()]
	dic = defaultdict(lambda : 0)
	dic1 = defaultdict(lambda : 0)
	for i in p:
		dic1[i] = 1
	for i in range(n):
		dic[l[i]] = i
	ans = 1
	for i in range(k):
		x = dic[p[i]]
		c = 0
		if x > 0 and dic1[l[x - 1]] == 0:
			c += 1
		if x < n - 1 and dic1[l[x + 1]] == 0:
			c += 1
		dic1[p[i]] = 0
		ans = ans * c % 998244353
	print(ans)


import sys
import math
input = sys.stdin.readline

def pi():
	return int(input())

def pl():
	return int(input(), 16)

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

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

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

def main():
	B()
nMap = [0 for i in range(200005)]
indexMap = [[] for i in range(200005)]
mod = 998244353

def B():
	t = pi()
	while t:
		t -= 1
		[n, k] = ti()
		a = ti()
		b = ti()
		mx = 0
		for i in range(n):
			mx = max(mx, a[i])
		for i in range(mx + 1):
			nMap[i] = 0
			indexMap[i].clear()
		for i in range(k):
			nMap[b[i]] += 1
		for i in range(n):
			indexMap[a[i]].append(i)
		res = 1
		for i in range(k):
			nMap[b[i]] = 0
			l = indexMap[b[i]]
			temp = 0
			for j in range(len(l)):
				if l[j] - 1 >= 0:
					if nMap[a[l[j] - 1]] == 0:
						temp += 1
				if l[j] + 1 < n:
					if nMap[a[l[j] + 1]] == 0:
						temp += 1
			res *= temp
		print(res % mod)
main()