We need to solve: Given initial array A (size N, with unique elements), target array T (which is a rotation of A, but we know it is guaranteed to be a rotated version). We have M operations, each either L X (left rotate by X) or R X (right rotate by X). These are applied sequentially starting from the initial array. If after performing an operation the array becomes equal to T, output the id (1-indexed) of that operation. If never, output -1.
Constraints up to 1e5 for N and M. X up to 1000, but N up to 1e5, so rotations need to be efficient.
We need to simulate the rotations without actually rotating array each time (since N large, but M also large, but total operations O(M) with O(1) per step is possible). Represent the current rotation offset relative to initial array.
Let A be original array. Let's define that the array at any time is a rotation of A. Since all elements unique, we can represent the state by an integer offset: the index in A that appears at position 0 (or at first position). But careful: Rotations: left rotate by X means shift left: each element moves X positions to the left (cyclic). Equivalent to rotating the array such that the element originally at index X (0-indexed) becomes the first element? Actually if we have array B (current), and we perform L X: new array B' where B'[i] = B[(i+X) mod N]. So if we think of the current rotation offset relative to original A, we can maintain an offset d such that current array B is: B[i] = A[(i + d) mod N]? Need to define precisely.
Let’s define: Suppose we have an offset start = s, meaning the element at index 0 of the current array corresponds to A[s] (0-indexed). That is, current = A rotated left by s? Actually if we start with initial array A, then s = 0 because current[0] = A[0]. Now left rotate by X: after left rotation, new start becomes (s + X) mod N? Let's check: initial B = A, s = 0. After L X, the element at new index 0 is old index X (since B'[0] = B[X] = A[X]). So new start = (0 + X) mod N = X. So left rotation adds X to start offset. Right rotation by X: R X. B'[0] = B[N-X]? Actually for right rotation: shifting elements to the right by X means B'[i] = B[(i - X) mod N]. So B'[0] = B[(-X mod N)] = B[N-X] (if X < N). So new start = (s + (N - X))? Let's compute: B'[0] = B[(0 - X) mod N] = B[(N - X) mod N] = A[(s + N - X) mod N]? Because B[k] = A[(k + s) mod N]. So B'[0] = B[(N-X) mod N] = A[((N-X) mod N + s) mod N] = A[(N-X + s) mod N]. So new start = (s + N - X) mod N = (s - X) mod N. Actually (s - X) mod N = (s + N - X) mod N. So right rotation by X subtracts X from start modulo N.
Thus we can maintain current offset s (0 <= s < N). Initially s = 0. Operation L X: s = (s + X) mod N. Operation R X: s = (s - X) mod N (or s = (s + N - X%N) mod N). Since X may be > N? X <= 1000 but N can be up to 1e5, so X < N? Not necessarily: X can be up to 1000, and N can be as low as 1, but then modulo works. However note: if X >= N, we should take X mod N? Actually rotation by X is effectively rotation by X mod N because rotating by N brings back to same. But the problem statement says "rotate the array towards left by X". It doesn't specify that X < N, but logically you can rotate by X > N, and it's equivalent to X mod N. Should we consider that? Since X <= 1000, it's okay to compute modulo N. But if N is small (e.g., N=2, X=1000) then rotating by 1000 is equivalent to rotating by 0 (since 1000 mod 2 = 0). But is that the intended behavior? Usually when rotating an array, rotating by X where X may be greater than the length, it's interpreted as rotating by X mod length. The problem statement doesn't say explicitly, but it's typical. However we need to verify from sample: Sample: N=4, last operation L 5. That rotates left by 5. Since N=4, L 5 is equivalent to L 1 (since 5 mod 4 = 1). But in the sample, after the third operation, they already got target, so the last operation is irrelevant. But they gave L 5, which would not cause match at 4? If we treat modulo, it's fine.
Given constraints X up to 1000, but N can be up to 1e5, so we can always compute X_mod = X % N. However careful: N can be 0? No, N >= 1.
Thus we can update offset efficiently.
Now we need to check after each operation whether the current rotated array equals target T.
Since T is a rotation of A, we need to check whether the offset s yields the array T. That is, we need to check if for all i, T[i] = A[(i + s) mod N]. However we need to handle the fact that A and T are given, with unique elements. Since T is guaranteed to be a rotation of A, there exists some offset t (0 <= t < N) such that T[i] = A[(i + t) mod N]. We need to find that t (maybe multiple? but unique because elements unique; if A has unique elements then rotation offset is unique unless N=1? But N>=1, if N=1 then rotation offset is always 0, but initial and target are different? Actually if N=1, then array with one element, rotations are same array, but note says initial and target arrays are different, so N cannot be 1 if they are different? But they said "It is guaranteed that the initial and target arrays are different." So they can be different, but if N=1, they can't be different because only one element. So N >= 2. So offset is unique.
So we can compute the offset k such that T matches A rotated by k. Then our simulation will match when s equals k (mod N). Since s is offset from initial A to current array: current array = A rotated left by s? Let's verify: With s = 0, current = A. After left rotate X, s = (s + X) mod N, and current[0] = A[s]. So indeed current = A rotated left by s (i.e., first element is A[s]). So T should match when s = t (where t is offset from A to T, i.e., T[0] = A[t]).
Thus we just need to find t. How to find t? Since elements are unique, we can locate the index of T[0] in A. But careful: It's possible that T[0] appears at multiple positions? Since unique, only one. So t = indexInA of T[0] (0-indexed). However is that always the correct offset? Let's test: If T is A rotated left by t, then T[0] = A[t]. So indeed t = position of T[0] in A. But we need to ensure the whole array matches that rotation. Since problem guarantees that T is a rotation of A, we can just find t from first element; no need to verify whole array? Actually problem guarantee: "Target array will always be a rotated version of the initial array". So if we compute t from first element, it must be the correct offset. However need to be careful: Could there be another rotation that also matches T? If unique elements, no. So fine.
But what if T[0] appears at index t, but due to some duplicate values? Not possible as unique. So we can simply compute target_offset = index of T[0] in A.
Edge: Need to handle case where N up to 1e5, so we can store a map from value to index.
Thus algorithm:
-
Read N, M.
-
Read initial array A (list of N ints).
-
Read target array T (list of N ints).
-
Build a dictionary mapping each value in A to its index. Since unique.
-
target_offset = pos[T[0]] (since T[0] is in A). But careful: If T is rotation of A, but we need to confirm direction? Actually T is just a rotation of A; it could be left or right? But rotation is cyclic; both left and right are rotations. So indeed T = A rotated by some offset d, where d in [0, N-1]. So using first element is fine.
-
Initialize current_offset = 0.
-
Loop through operations i from 1 to M:
- read op: either "L X" or "R X". Parse X.
- compute effective shift = X % N. If N is large, X%N = X (since X<=1000, N up to 1e5, so it's X if N > X, but if N small, we need mod). Compute mod.
- If op is L: current_offset = (current_offset + effective_shift) % N.
- else: current_offset = (current_offset - effective_shift) % N (ensure positive mod N: current_offset = (current_offset - effective_shift + N) % N).
- After updating, check if current_offset == target_offset.
- If true, output i and exit.
-
If loop ends, output -1.
That's it. Complexity O(N+M) time, O(N) space.
Let's test with sample:
N=4, M=4.
A = [2,1,3,4]; T = [3,4,2,1];
Map: 2->0, 1->1, 3->2, 4->3.
target_offset = index of T[0]=3 => 2.
current_offset = 0.
Ops:
- R 1: effective shift 1%4=1. R: current_offset = (0 -1 +4)%4 = 3. Check 3 !=2.
- L 2: shift=2. current_offset = (3+2)%4=1. !=2.
- L 1: shift=1. current_offset = (1+1)%4=2. == target_offset => output 3.
Matches sample.
So answer is 3.
Edge cases:
- If N=2, A=[1,2], T=[2,1], target_offset = index of T[0]=2? Actually A: index 0:1, index1:2. T[0]=2 => target_offset=1.
- Simulation works.
Now note: Since target array is guaranteed to be a rotation, the answer will be found if some operation makes s = target_offset. However, it's possible that target_offset is unreachable? But since we can perform arbitrary rotations left/right, we can achieve any offset because we can adjust by any X, but X may not allow reaching exactly target_offset? Actually since we can apply many operations sequentially, the set of reachable offsets after each operation is any integer modulo N because we can combine operations. But we need to check if exactly at some step offset equals target_offset. Starting from 0, each operation changes offset by ± X mod N. So it's like we walk on cyclic group Z_N. The set of offsets visited after each operation are the partial sums modulo N. The question asks to output the first i where offset equals target_offset. So we simulate.
Given N up to 1e5, M up to 1e5, X up to 1000, mod operations fine.
Now implement.
Potential pitfalls:
- Input reading: M lines each like "L 100". Use split.
- Need to compute modulo N for shifts; but careful: if N == 0? Not possible.
- Since X up to 1000 and N can be as low as 1? But initial and target different, so N at least 2. So N>=2.
But what if N = 2 and X = 3? X%2 = 1, effective shift = 1.
All good.
Now we must confirm mapping: if T[0] appears in A at index pos. But guarantee ensures it does.
Double-check: Could T be a rotation but not necessarily starting with an element from A? It must, as rotation. So yes.
Now we need to consider that the initial and target arrays are different, so target_offset != 0. So answer cannot be 0 before any operations.
Now confirm output: print id (1-indexed) or -1.
Implementation details:
- Use sys.stdin.read().split() to parse quickly.
- But careful: operations lines contain a character and an integer. So we can read all tokens.
Approach: Read first line: N, M. Then read N ints for A, N ints for T. Then M lines: each with a char and an int. So total tokens = 2 + N + N + 2*M. So read all tokens.
Pseudo:
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
N = int(next(it))
M = int(next(it))
A = [int(next(it)) for _ in range(N)]
T = [int(next(it)) for _ in range(N)]
# build index map
idx = {val:i for i,val in enumerate(A)}
target_offset = idx[T[0]] # since unique
cur = 0
# precompute N maybe zero? no
for i in range(1, M+1):
op = next(it)
X = int(next(it))
eff = X % N if N != 0 else 0 # N>=1
if op == 'L':
cur = (cur + eff) % N
else: # 'R'
cur = (cur - eff) % N
if cur == target_offset:
print(i)
return
print(-1)
But we should note: operation character might be "L" or "R" exactly. So fine.
Now let's consider edge-case: N could be 1? But problem says initial and target are different, and they are both arrays of N unique elements? If N=1, only one element, so unique, but they cannot be different. So N>=2. So safe.
Time complexity: O(N+M). Memory O(N) for map.
Now test with some other scenarios:
Case: N=5, A=[1,2,3,4,5], T=[5,1,2,3,4] (right rotation by 1 => left rotation by 4). target_offset = index of 5 => 4. Simulate: if first operation R 1: cur = (0-1)%5=4 => match => output 1.
Case: If multiple operations cause match at later step, ok.
Case: if never: e.g., N=3, A=[1,2,3], T=[2,3,1] => target_offset=1. Operations: L 1 (cur=1) match at op1. So answer 1.
Case: never: maybe due to weird offsets? But if we simulate all, if never equal, output -1.
Now, note: Because X can be large relative to N, we use mod. But is it possible that rotating by X where X > N should be done as multiple full rotations? In programming, we typically reduce modulo N. The problem statement doesn't specify, but mathematically rotating by X is the same as rotating by X mod N. The sample includes L 5 with N=4, which is effectively 1 left rotation. So likely they expect modulo.
But what if N=0? Not possible.
Thus solution is straightforward.
But before finalizing, consider alternative interpretation: Could the operations be cumulative on the current state, but they might be applied to the array as physical rotation each time? But our representation handles that.
Now, check if any nuance: The problem says "rotate the array towards left by X". It might be that X can be larger than N, but it's still valid and we rotate as many times; but we can just do modulo. However, the note says 1 ≤ X ≤ 1000, so X is small relative to N often, but if N is also small, then modulo needed.
Thus algorithm is correct.
Now, note about building map: Since Ai, Ti up to 1e9, using dictionary works.
Now think about potential issue: Could there be multiple rotations that match T? For unique elements, no. But consider scenario where A = [1,2,3,4] and T = [1,2,3,4] (initial == target) but problem says they are different, so not case.
Ok.
Thus answer: implement as described.
Now, we need to print output in a single line.
Testing with sample: yields 3.
Now, writing code.
But wait: There's one subtlety: The definition of offset with L and R might be opposite if we choose a different representation. Let's double-check thoroughly with a few examples to ensure our update formulas are correct.
Define current array cur as: cur[i] = A[(i + s) % N], where s is the index in A that appears at position 0 of cur. Start: s=0 => cur = A.
Now apply L X: According to definition, left rotate by X: new[i] = cur[(i+X) % N]. So new[0] = cur[X] = A[(X + s) % N]. Thus new start = (s + X) % N. So s becomes (s+X)%N. Good.
Apply R X: Right rotate by X: new[i] = cur[(i - X) % N]. So new[0] = cur[(-X)%N] = cur[N-X] if X < N. cur[N-X] = A[((N-X) + s) % N] = A[(s + N - X) % N] = A[(s - X) % N]. So new start = (s - X) % N. So s = (s - X) % N. Good.
Now find target offset: We want cur to equal T. Since T is rotation of A, there exists t such that T[i] = A[(i + t) % N] for all i. Then cur equals T iff s = t (mod N). So match when s == t.
Thus correct.
Now code in Python.
But ensure that when N is large, we compute X % N correctly: X % N may be computationally cheap; but for performance we can compute if X >= N: X %= N else X remains same. But using % is fine.
Edge: N may be 1? Not allowed, but if it were, modulo by 1 gives 0. But then initial and target are different? impossible. So ignore.
Now a nuance: The target array could be a rotation, but maybe not with the same direction? Actually rotation of an array is unique up to direction; left vs right are symmetric: left by X is same as right by N-X. So our representation covers all.
Now the solution is trivial.
But we must think: Could there be any trap with the mapping? For example, if T is given as a rotated version, but not necessarily starting with an element present in A? That would be impossible since all elements in T are from A, but because elements are unique, the position of T[0] in A determines the rotation offset. However, what if there are duplicates? But problem says unique elements, so fine.
Thus solution is good.
Now let's think about potential large input: M=100k, reading via sys.stdin.read().split() is okay. Memory: tokens ~ (2+2N+2M) up to ~400k tokens, fine.
Implementation:
def solve():
import sys
data = sys.stdin.buffer.read().split() # using buffer for faster
it = iter(data)
N = int(next(it))
M = int(next(it))
A = [int(next(it)) for _ in range(N)]
T = [int(next(it)) for _ in range(N)]
# Build index map
idx = {v:i for i,v in enumerate(A)}
target_offset = idx[T[0]]
cur = 0
N_mod = N
for i in range(1, M+1):
op = next(it).decode()
X = int(next(it))
eff = X % N_mod
if op == b'L'? Actually if using buffer, items are bytes, so we need to compare to b'L'. So we can do:
op = next(it) # bytes
if op == b'L':
cur = (cur + eff) % N_mod
else: # b'R'
cur = (cur - eff) % N_mod
if cur == target_offset:
print(i)
return
print(-1)
Yes.
Alternatively, we can read line by line but buffer read is faster.
Now check correctness with a few random tests.
We can write a small brute-force simulation for small N to verify.
But given the reasoning, it's fine.
Now, maybe there is a twist: The arrays contain unique elements but large up to 1e9, but that's fine.
Now think about the note: "Target array will always be a rotated version of the initial array". So indeed it's guaranteed.
Now one more nuance: Could the target array be the initial array rotated by some amount that is not representable as a single offset? No, any rotation yields an offset.
Thus final answer: implement as above.
But wait: There's an alternative scenario: The operations are applied serially, but we need to output the id of the operation after which the array becomes same as target. That is, after performing operation i, we check. So if initial array already matches target? But they said they are different, so not.
Now, we could also think of precomputing all offsets after each operation by cumulative sum and then checking equality. But we can just simulate.
Thus final solution is O(M).
Now, before concluding, ensure that we treat X mod N correctly when N = 0? Not applicable.
Now, is there any possibility that the rotation is performed as physical rotation each time, and X might be larger than N but we still rotate step by step? That would be inefficient. But mathematically it's the same as modulo.
But suppose X = 10^6? But constraints say X <= 1000, so fine.
Now, what about multiple test cases? The problem statement seems to indicate a single test case. So we output only one answer.
Now, let's think about whether the array after rotation might be considered different if we treat rotations as moving elements, but it's same as our offset method.
Now, is there any scenario where offset equals target_offset but the arrays are not equal due to some mismatch? Since T is guaranteed to be a rotation, offset match ensures equality for all indices because the mapping from A to T via offset is one-to-one. But is it possible that the target offset we compute from first element is not the unique rotation? Suppose A = [1,2,3,4], T = [3,4,1,2] (which is rotation left by 2). T[0]=3, index in A=2. So offset=2 yields correct mapping. Indeed T[i] should equal A[(i+2)%4]. Check: i=0: A[2]=3 ok; i=1: A[3]=4 ok; i=2: A[0]=1 ok; i=3: A[1]=2 ok. So works.
If T is a rotation but maybe they consider right rotations differently? Actually any rotation can be expressed as left rotation by some amount. So fine.
Thus solution stands.
Now write final answer accordingly.
However, the problem might have some hidden nuance: Could the target array be a rotation but not necessarily using the same ordering? For example, A = [1,2,3,4]; T = [4,3,2,1]? That is not a rotation; it's reverse. Problem says target array will always be a rotated version, so not.
So final.
Now double-check sample with code: We already did.
Potential issue: The use of dictionary mapping from value to index for A: Since values up to 1e9, dictionary is fine.
Now, what about memory? N up to 1e5, dictionary with 1e5 entries, fine.
Now, note: If N is large (1e5) and M is large (1e5), operations loops are 1e5, each doing constant time, fine.
Now, we should also consider that we need to decode op if we use bytes. Alternatively, we can read line by line with sys.stdin.readline() for clarity, but still fine.
Now produce final solution.
But we must also ensure to convert op correctly: In Python, when using buffer read and split, tokens are bytes. So comparing to b'L' and b'R' is safe.
Now, code.
Now, maybe there is a trick: The target array may be a rotated version, but if we compute offset from T[0], we must be careful: if N is large and values repeated? But unique.
Now, is there any case where T[0] appears in A at some index, but the rotation that matches T is a different offset because T is not a rotation? No, it's guaranteed.
Thus final.
Now, let's write final answer.
Implementation:
import sys
def main():
import sys
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
A = [int(next(it)) for _ in range(n)]
T = [int(next(it)) for _ in range(n)]
pos = {v:i for i,v in enumerate(A)}
target = pos[T[0]]
cur = 0
for i in range(1, m+1):
op = next(it)
x = int(next(it))
shift = x % n
if op == b'L':
cur = (cur + shift) % n
else: # 'R'
cur = (cur - shift) % n
if cur == target:
sys.stdout.write(str(i))
return
sys.stdout.write("-1")
if name == "main":
main()
That's it.
Now consider if n=0? Not needed.
Thus final answer.
Now we can produce explanation.
But before finalize, let's test with a custom case to ensure modulo works correctly when N is small.
Case: N=2, A=[1,2], T=[2,1] -> target=1.
Operations: M=2, L 3, R 1.
Step1: L 3, shift=3%2=1, cur= (0+1)%2=1 -> matches, output 1. That's correct because left rotate by 3 (which is 1 mod 2) yields [2,1]. So answer 1.
Case: N=3, A=[10,20,30], T=[20,30,10] (left rotate by 1 -> target offset index of 20 =1). Operations: R 2. shift=2%3=2. cur = (0-2)%3=1 -> matches, output 1. Because right rotate by 2 is same as left rotate by 1. Good.
Now, case where X mod N is 0: e.g., N=5, X=10 -> shift=0, so operation does nothing. Our code handles: cur unchanged, then check.
Now, consider possibility: target_offset computed from T[0] is correct, but maybe we should also verify the entire array? Not needed per constraints.
Now, one more nuance: The problem says "two arrays containing N unique elements". That means both arrays have unique elements individually, but are the elements across arrays the same set? It says target array is a rotated version of initial array, so yes, they contain exactly same elements, just order changed. So all elements of T appear in A. So mapping exists.
Now, final.
Thus answer is to output first operation id where cumulative offset equals the offset of the first element of target in initial array.
Edge-case: If after some operation the array matches target, we output id and stop. If never, output -1.
Now, produce final answer with code and explanation.
But wait: There's a potential pitfall: The offset representation uses left rotation. However, what if we consider direction differently? Let's double-check with a scenario where we apply right rotation and verify offset change.
Example: A = [1,2,3,4,5]; start cur=0 => [1,2,3,4,5].
Apply R 2: According to our update, cur = (0-2)%5 = 3. So cur=3 => array should be A starting at index 3: A[3]=4, A[4]=5, A[0]=1, A[1]=2, A[2]=3 => [4,5,1,2,3]. Now, does right rotate by 2 of [1,2,3,4,5] produce [4,5,1,2,3]? Right rotate by 2: shift elements to right; last two move to front: [4,5,1,2,3]. Yes. Good.
Now, left rotate by 2: cur = (0+2)%5 =2 => [3,4,5,1,2]. Which is correct.
Thus correct.
Now, confirm mapping for target: If T = [4,5,1,2,3], then target_offset = index of 4 in A = 3. So matches.
Thus all good.
Now, potential large M but small N, we compute many mod operations; still fine.
Now, we may also consider using a precomputed cumulative offset and check if at any step (cumulative offset modulo N) equals target. This is same as simulation.
Now, what about reading input: The M lines: each with a char and an integer. Using data = sys.stdin.read().split() will treat each token separately; the char is a token, the integer is token. So we will get alternating char, int. That's fine.
Now, final answer.
But I'd like to also discuss possibility of not using dictionary but simply scanning A to find T[0] index. Since N up to 1e5, scanning O(N) is fine. But dictionary is O(1) average, but scanning also O(N) which is fine as N up to 1e5. However, we already have O(N) to read A; scanning again to find index is O(N) which is acceptable. But dictionary simplifies. However, building dictionary also O(N). So both fine.
Now, ensure to handle negative modulo: Python's % already returns non-negative remainder, so (cur - shift) % n yields correct non-negative result. So we can just do cur = (cur - shift) % n. So we don't need +n.
Now, final code:
import sys
def solve():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
A = [int(next(it)) for _ in range(n)]
T = [int(next(it)) for _ in range(n)]
# find offset of target
# Since elements are unique, find index of T[0] in A
# Using dictionary for O(1)
index_map = {value: i for i, value in enumerate(A)}
target_offset = index_map[T[0]]
cur_offset = 0
for i in range(1, m+1):
op = next(it)
x = int(next(it))
shift = x % n
if op == b'L':
cur_offset = (cur_offset + shift) % n
else: # 'R'
cur_offset = (cur_offset - shift) % n
if cur_offset == target_offset:
sys.stdout.write(str(i))
return
sys.stdout.write("-1")
if name == "main":
solve()
Now, let's run with sample.
Sample input:
4 4
2 1 3 4
3 4 2 1
R 1
L 2
L 1
L 5
Our code: data tokens: ['4','4','2','1','3','4','3','4','2','1','R','1','L','2','L','1','L','5'] (bytes). It will parse correctly: n=4,m=4; A=[2,1,3,4]; T=[3,4,2,1]; map: {2:0,1:1,3:2,4:3}; target_offset = index of 3 = 2; loop: i=1 op='R' x=1 shift=1%4=1 cur=(0-1)%4=3; not equal; i=2 op='L' x=2 shift=2 cur=(3+2)%4=1; not; i=3 op='L' x=1 shift=1 cur=(1+1)%4=2 equal => output 3. Good.
Now, test with an edge-case: N=2 M=1 A=1 2 T=2 1 ops: L 3 => shift=3%2=1 cur=1 matches -> output 1. Good.
Now, also test case where target_offset reached after multiple ops, but earlier not.
Case: N=10, A arbitrary, target_offset=3. Simulate some random ops to confirm.
Thus final.
Now, output format: "Print a single line containing the required answer."
So done.
But wait: The problem statement says: "Now you will be given 2 arrays containing N unique elements. The first one is the initial array(A) and the second one is target array(T)." It also says: "Note: It is guaranteed that the initial and target arrays are different. Note: Target array will always be a rotated version of the initial array". So we've used that.
One more nuance: What if the initial array and target array are different but have same elements? They guarantee rotated version, so yes.
Thus answer correct.
Now, we can produce final explanation: We maintain a current rotation offset, update based on operations, and check equality to the target offset.
Now, I'll craft final response with explanation and code. We can maintain the current state as a rotation offset from the original array.
Let the initial array be A (0‑indexed). We keep an integer cur such that the current array is
B[i] = A[(i + cur) % N]. Initially cur = 0.
- A left rotation by
X shifts the start index forward: cur = (cur + X) % N.
- A right rotation by
X shifts the start index backward: cur = (cur - X) % N.
Because rotating by X is the same as rotating by X mod N, we use the effective shift X % N.
The target array T is guaranteed to be a rotation of A, so there exists a unique offset target with
T[i] = A[(i + target) % N] for all i. Since all elements are distinct, target is simply the index of T[0] in A.
We simulate the M operations in order. After each update we compare cur with target. If they become equal, we output the operation number (1‑indexed). If no equality occurs, we output -1.
This runs in O(N + M) time and O(N) memory.
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
A = [int(next(it)) for _ in range(n)]
T = [int(next(it)) for _ in range(n)]
# index of each value in A (all values are unique)
pos = {v: i for i, v in enumerate(A)}
target = pos[T[0]]
cur = 0
for i in range(1, m + 1):
op = next(it) # b'L' or b'R'
x = int(next(it))
shift = x % n
if op == b'L':
cur = (cur + shift) % n
else: # b'R'
cur = (cur - shift) % n
if cur == target:
sys.stdout.write(str(i))
return
sys.stdout.write("-1")
if __name__ == "__main__":
solve()