Problem:


Score : 700 points

Problem Statement

We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}).
Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.

Snuke has an integer sequence s, which is initially empty.
For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:

If s does not contain X_i: add X_i to the end of s.

If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.

Find the elements of s after Snuke finished the operations.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq K \leq 10^{12}

1 \leq A_i \leq 2 \times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 \cdots A_{N-1}

Output

Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.

Sample Input 1

3 2
1 2 3

Sample Output 1

2 3

In this case, X=(1,2,3,1,2,3).
We will perform the operations as follows:

i=0: s does not contain 1, so we add 1 to the end of s, resulting in s=(1).

i=1: s does not contain 2, so we add 2 to the end of s, resulting in s=(1,2).

i=2: s does not contain 3, so we add 3 to the end of s, resulting in s=(1,2,3).

i=3: s does contain 1, so we repeatedly delete the element at the end of s as long as s contains 1, which causes the following changes to s: (1,2,3)→(1,2)→(1)→().

i=4: s does not contain 2, so we add 2 to the end of s, resulting in s=(2).

i=5: s does not contain 3, so we add 3 to the end of s, resulting in s=(2,3).

Sample Input 2

5 10
1 2 3 2 3

Sample Output 2

3

Sample Input 3

6 1000000000000
1 1 2 2 3 3

Sample Output 3

s may be empty in the end.

Sample Input 4

11 97
3 1 4 1 5 9 2 6 5 3 5

Sample Output 4

9 2 6



Sample input:
3 2
1 2 3


Sample output:
2 3

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import defaultdict
N,K = map(int,input().split())
A = list(map(int,input().split()))

#N = 2*10**5
#K = 10**12
#A = [(i % 200000) + 1 for i in range(N)]

B = A * 2

NA = [-1]*N
d = {}
for i, b in enumerate(B):
    if b in d:
        if NA[d[b]%N] == -1:
            NA[d[b]%N] = i - d[b]+1
        d[b] = i 
    else:
        d[b] = i

L = 70
ds = [NA]
for i in range(L):
    temp = []
    pre = ds[-1]
    for j in range(N):
        t = pre[j]
        t += pre[((t+j)%N)]
        temp.append(t)
    ds.append(temp)

cnt = 0
i = 0

L -= 1
NA = ds[L]
while True:
    add = NA[i]
    nxt = ((i + add)%N)
    if cnt + add > N*K:
        L -= 1
        if L < 0:
            break
        NA = ds[L]
        continue
    cnt += add
    i = nxt

rest = N*K - cnt

s = []
d = {}
for j in range(rest):
    a = A[i]
    if a in d:
        s = s[:d[a]]
        del d[a]
    else:
        d[a] = j
        s.append(A[i])
    i += 1
    i %= N

print(*s)

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N, K = mapint()
As = list(mapint())
double_As = As*2

idx_dic = {}
idx_lis = [N]*(2*N)
for i in range(N*2-1, -1, -1):
    a = double_As[i]
    if a in idx_dic:
        idx_lis[i] = idx_dic[a]
    idx_dic[a] = i
print(idx_lis)
doubling = [[0]*N for _ in range(60)]
accum = [[0]*N for _ in range(60)]
doubling[0] = [i%N for i in idx_lis[:N]]
accum[0] = [a-i for i, a in enumerate(idx_lis[:N])]
for i in range(1, 60):
    for j in range(N):
        doubling[i][j] = doubling[i-1][doubling[i-1][j]]
        accum[i][j] = accum[i-1][j] + accum[i-1][doubling[i-1][j]]

now = 0
print(doubling)
for i in range(60):
    if doubling[i][now]>N*K:
        continue
    else:
        now = doubling[i][now]
        print(now)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

import bisect

def main():
	n,k=MI()
	A=LI()
	B=[[] for _ in range(2*10**5+10)]

	for i,v in enumerate(A):
		B[v-1].append(i)

	for li in B:
		if li:
			li.append(li[0])

	#print(A)
	#print(B)

	C=[0]

	s=0

	while True:
		a=A[s]-1
		ti=bisect.bisect_left(B[a][:-1],s)+1
		t=B[a][ti]
		#print(s,t)
		if t==n-1:
			break
		else:
			if s>=t:
				C.append(s)
			s=t+1
	#print(C)

	k%=len(C)
	#print(k)

	if k==0:
		print(*[])
		exit()



	s=C[k]
	#print(s)

	ans=[]

	while s<n:
		a=A[s]-1
		si=bisect.bisect_left(B[a][:-1],s)
		if si+1==len(B[a][:-1]):
			ans.append(a+1)
			s+=1
		else:
			s=B[a][si+1]+1
	print(*ans)



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

import bisect

def main():
	n,k=MI()
	A=LI()
	B=[[] for _ in range(2*10**5+10)]

	for i,v in enumerate(A):
		B[v-1].append(i)

	for li in B:
		if li:
			li.append(li[0])

	#print(A)
	#print(B)

	C=[0]

	s=0

	while True:
		a=A[s]-1
		ti=bisect.bisect_left(B[a][:-1],s)+1
		t=B[a][ti]
		#print(s,t)
		if t==n-1:
			break
		else:
			if s>=t:
				C.append(s)
			s=t+1
	#print(C)

	k%=len(C)
	#print(k)

	if k==0:
		print()
		exit()



	s=C[k]
	#print(s)

	ans=[]

	while s<n:
		a=A[s]-1
		si=bisect.bisect_left(B[a][:-1],s)
		if si+1==len(B[a][:-1]):
			ans.append(a+1)
			s+=1
		else:
			s=B[a][si+1]+1
	print(*ans)



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

import bisect

def main():
	n,k=MI()
	A=LI()
	B=[[] for _ in range(2*10**5+10)]

	for i,v in enumerate(A):
		B[v-1].append(i)

	for li in B:
		if li:
			li.append(li[0])

	#print(A)
	#print(B)

	C=[0]

	s=0

	while True:
		a=A[s]-1
		ti=bisect.bisect_left(B[a][:-1],s)+1
		t=B[a][ti]
		#print(s,t)
		if t==n-1:
			break
		else:
			if s>=t:
				C.append(s)
			s=t+1
	#print(C)

	k%=len(C)
	#print(k)

	s=C[k]
	#print(s)

	ans=[]

	while s<n:
		a=A[s]-1
		si=bisect.bisect_left(B[a][:-1],s)
		if si+1==len(B[a][:-1]):
			ans.append(a+1)
			s+=1
		else:
			s=B[a][si+1]+1
	print(*ans)



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
def examA():
    N = DI()/dec(7)
    ans = N
    print(N)
    return

def examB():
    N, K = LI()
    A = LI()
    maxA = max(A)

    def function(s):
        stack = deque()
        num = [0]*(maxA+1)
        for i in range(s,N):
            a = A[i]
            if num[a]==0:
                stack.append(a)
                num[a] += 1
            else:
                while(num[a]>0):
                    num[stack.pop()] -= 1

        return stack

    B = [-1 for _ in range(N)]
    que = {}
    for i in range(N):
        a = A[i]
        if a not in que:
            que[a] = i
        else:
            prev = que.pop(a)
            B[prev] = i - prev
            que[a] = i
    i = 0
    while(que):
        a = A[i]
        if a in que:
            prev = que.pop(a)
            B[prev] = N + i - prev
        i += 1
    #print(B)
    locat_doubling = [[-1]*N for _ in range(61)]

    for i in range(N):
        locat_doubling[0][i] = 0
        locat_doubling[1][i] = B[i] + 1

    for k in range(2,31):
        for i in range(N):
            locat_doubling[k][i] = locat_doubling[k-1][i] + locat_doubling[k-1][(i+locat_doubling[k-1][i])%N]
    #print(locat_doubling[:5])
    now = 0
    rest = K*N
    for i in range(61)[::-1]:
        if locat_doubling[i][now]<=rest:
            rest -= locat_doubling[i][now]
            now = (locat_doubling[i][now]+now)%N
    #print(rest,now)

    ans = function(now)
    print(" ".join(map(str,ans)))
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
aa=a+a
lp=[-1]*n
dn={}
for i in range(2*n):
    x=aa[i]
    if x in dn:
        dn[x].append(i)
    else:
        dn[x]=[i]
from bisect import bisect_right
now_idx=0
ka=set(())
cnt=1
while True:
    v=a[now_idx]
    tmp=bisect_right(dn[v],now_idx)
    next_idx=dn[v][tmp]
    if next_idx>=n:
        cnt+=1
        next_idx%=n
    if next_idx in ka:
        break
    ka.add(next_idx)
    lp[next_idx]=cnt
    now_idx=next_idx+1
    now_idx%=n
ml=max(lp)
k%=ml
ans=[]
#print(lp,k)
c=set(())
for i in range(n):
    if lp[-1-i]==-1 or lp[-1-i]%ml!=k:
        if a[-1-i] in c:
            ans=[]
            c=set(())
        else:
            ans.append(str(a[-1-i]))
            c.add(a[-i-1])
    else:
        break
ans.reverse()
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
aa=a+a
lp=[-1]*n
dn={}
for i in range(2*n):
    x=aa[i]
    if x in dn:
        dn[x].append(i)
    else:
        dn[x]=[i]
from bisect import bisect_right
now_idx=0
ka=set(())
cnt=1
while True:
    v=a[now_idx]
    tmp=bisect_right(dn[v],now_idx)
    next_idx=dn[v][tmp]
    if next_idx>=n:
        cnt+=1
        next_idx%=n
    if next_idx in ka:
        break
    ka.add(next_idx)
    lp[next_idx]=cnt
    now_idx=next_idx+1
    now_idx%=n
ml=max(lp)
k%=ml
ans=[]
#print(lp,k)
c=set(())
for i in range(n):
    if lp[-1-i]%ml!=k:
        if lp[-1-i]!=-1 and a[-1-i] in c:
            ans=[]
            c=set(())
        else:
            ans.append(str(a[-1-i]))
            c.add(a[-i-1])
    else:
        break
ans.reverse()
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
aa=a+a
lp=[-1]*n
dn={}
for i in range(2*n):
    x=aa[i]
    if x in dn:
        dn[x].append(i)
    else:
        dn[x]=[i]
from bisect import bisect_right
now_idx=0
ka=set(())
cnt=1
while True:
    v=a[now_idx]
    tmp=bisect_right(dn[v],now_idx)
    next_idx=dn[v][tmp]
    if next_idx>=n:
        cnt+=1
        next_idx%=n
    if next_idx in ka:
        break
    ka.add(next_idx)
    lp[next_idx]=cnt
    now_idx=next_idx+1
    now_idx%=n
ml=max(lp)
k%=ml
ans=[]
#print(lp,k)
c=set(())
for i in range(n):
    if lp[-1-i]%ml!=k:
        if a[-1-i] in c:
            ans=[]
            c=set(())
        else:
            ans.append(str(a[-1-i]))
            c.add(a[-i-1])
    else:
        break
ans.reverse()
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
a = inl()

# nxt loc for each val
prev = [-1]*200001
nxt = [-1]*(n+1)
for i in range(2*n):
    v = a[i%n]
    if 0<=prev[v]<n:
        nxt[prev[v]] = (i+1)%n
    prev[v] = i
#ddprint("nxt")
#ddprint(nxt)

# find loop
last = [-1]*(2*n)
cur = 0
cyc = 0
dolast = False
for i in range(2*n):
    last[cur] = cyc
    nx = nxt[cur]
    if nx<cur+2:
        if cyc==k-1:
            dolast = True
            break
        cyc += 1
    cur = nx
    if last[nx]>=0:
        break
#ddprint(f"1 {cyc=} {cur=} last {last[nx]}")

if not dolast:
    # loop: last[cur]*n + cur .. cyc*n + cur
    d = cyc-last[nx]
    cyc += ((k-1-cyc)//d)*d
    #ddprint(f"2 {cyc=} {cur=} {d=} last {last[nx]}")

    # cyc*n + cur
    while cyc<k:
        nx = nxt[cur]
        if nx<cur+2:
            if cyc==k-1:
                break
            cyc += 1
        cur = nx
#ddprint(f"3 {cyc=} {cur=}")

# last one mile
last = [-1]*200001
b = [a[cur]]
last[a[cur]] = cur
for i in range(cur+1,n):
    j = last[a[i]]
    if j>=0:
        while b[-1]!=a[i]:
            last[b[-1]] = -1
            b.pop()
        last[b[-1]] = -1
        b.pop()
    else:
        b.append(a[i])
        last[a[i]] = i

# output
pad = ''
for x in b:
    printn(pad+str(x))
    pad = ' '
print('')

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint
from copy import deepcopy


sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 998244353


n, k = LI()
A = LI()
D = defaultdict(list)
for i in range(n):
    D[A[i]] += [i]


nxt_idx = [0] * n
for idx_list in D.values():
    for j in range(len(idx_list)):
        nxt_idx[idx_list[j]] = idx_list[(j + 1) % len(idx_list)]



ret = 0
now = 0
L = []
visited = set()
while now not in visited:
    visited.add(now)
    nxt = nxt_idx[now]
    diff = (nxt - now) % n if nxt != now else n
    now = (nxt + 1) % n
    ret += diff + 1
    L += [[ret - 1, nxt]]


ll = (n * k - 1) % ret
bb = bisect_right(L, [ll, INF]) - 1
cc, last_idx = L[bb]
ans = []
ss = set()
for i in range(ll - cc):
    a = A[(last_idx + i + 1) % n]
    if a in ss:
        while a in ss:
            ss.remove(ans.pop())
    else:
        ans += [a]
        ss.add(a)

print(*ans)

Submission status: Wrong Answer

Solution code:
import collections

n,k=map(int,input().split())
arr=list(map(int,input().split()))
pos=[[] for _ in range(max(arr)+1)]
for i in range(2*n):
  pos[arr[i%n]].append(i)
edge=[[] for _ in range(n)]
cnt=collections.defaultdict(int)
for i in range(n):
  s=pos[arr[i]][cnt[arr[i]]]
  g=pos[arr[i]][cnt[arr[i]]+1]
  if g+1<n:
    edge[s].append(g+1)
    edge[s].append(0)
  else:
    edge[s].append((g+1)%n)
    edge[s].append(1)
  cnt[arr[i]]+=1
start=0
loop=0
for _ in range(n):
  loop+=edge[start][1]
  start=edge[start][0]
  if start==0:
    break
k%=loop
if k==0:
  print('')
else:
  k-=1
  start=0
  loop=0
  for _ in range(n):
    if loop==k:
      break
    loop+=edge[start][1]
    start=edge[start][0]
  s=set()
  q=collections.deque()
  for i in range(start,n):
    if arr[i] not in s:
      s.add(arr[i])
      q.append(arr[i])
    else:
      while 1:
        tmp=q.pop()
        s.discard(tmp)
        if tmp==arr[i]:
          break
  print(*list(q))

Submission status: Wrong Answer

Solution code:
from bisect import bisect_right
from collections import defaultdict

N, K = map(int, input().split())
*A, = map(int, input().split())
dd = defaultdict(list)

for i, j in enumerate(A):
    dd[j].append(i)

conv = [0] * (N+1)
for i, j in enumerate(A):
    pos = i

    while pos < N:
        v = A[pos]
        p = bisect_right(dd[v], pos)
        size = len(dd[v])
        if p < size:
            pos = dd[v][p]+1
            if pos == N:
                conv[i] = 0
                break
        else:
            conv[i] = dd[A[pos]][0] + 1
            break
conv[N] = 0

dp = [[0]*(N+1) for _ in range(20)]
for i in range(N+1):
    dp[0][i] = conv[i]

for k in range(1, 20):
    for n in range(N+1):
        dp[k][n] = dp[k - 1][dp[k - 1][n]]

res = []
t = K-1
for i in range(20):
    if (t>>i)&1:
        res.append(i)
    
pos = 0
for i in res:
    pos = dp[i][pos]

ans = []
while pos < N:
    num = A[pos]
    pp = bisect_right(dd[num], pos)
    if pp < len(dd[num]):
        pos = dd[num][pp]+1
    else:
        ans.append(num)
        pos += 1
print(*ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect_right

N, K = map(int, input().split())
*A, = map(int, input().split())

dd = defaultdict(list)
for i, j in enumerate(A):
    dd[j].append(i)

pos = 0
loop = 1
# l = []
cic = defaultdict(list)

while pos < N:
    num = A[pos]
    
    pp = bisect_right(dd[num], pos)
    if pp < len(dd[num]):
        pos = dd[num][pp]+1
    else:
        pos = dd[num][0]+1            
        loop += 1
    # l.append((pos, loop))
    cic[loop].append(pos)

# for pos, v in l:
#     if (K-v)%loop==0:
#         break

if not cic[K%loop]:
    print()
else:
    pos = cic[K%loop][0] #pos if pos<N else 0
    ans = []
    while pos < N:
        num = A[pos]
        pp = bisect_right(dd[num], pos)
        if pp < len(dd[num]):
            pos = dd[num][pp]+1
        else:
            ans.append(num)
            pos += 1
    print(*ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, Counter
from bisect import bisect_right, bisect_left

N, K = map(int, input().split())
*A, = map(int, input().split())

c = Counter(A)
target = []
d = defaultdict(list)

dd = defaultdict(list)
for i, j in enumerate(A):
    dd[j].append(i)

pos = 0
loop = 1
l = []

while pos < N:
    num = A[pos]
    
    pp = bisect_right(dd[num], pos)
    if pp < len(dd[num]):
        pos = dd[num][bisect_right(dd[num], pos)]+1
    else:
        pos = dd[num][0]+1            
        loop += 1
    l.append((num, pos, loop))

for v, pos, p in l[::-1]:
    if (K-p)%loop==0:
        break

start = pos
if pos >= N:
    print(v)
else:
    res = []
    for i in range(start, N):
        if A[i] in res:
            res = res[:res.index(A[i])]
        else:
            res.append(A[i])

    print(*res)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, Counter
from bisect import bisect_right, bisect_left

N, K = map(int, input().split())
*A, = map(int, input().split())

c = Counter(A)
target = []
d = defaultdict(list)

dd = defaultdict(list)
for i, j in enumerate(A):
    dd[j].append(i)

pos = 0
loop = 1
l = []

while pos < N:
    num = A[pos]
    
    pp = bisect_right(dd[num], pos)
    if pp < len(dd[num]):
        pos = dd[num][bisect_right(dd[num], pos)]+1
    else:
        pos = dd[num][0]+1            
        loop += 1
    l.append((num, pos, loop))

for v, pos, p in l:
    if (K-p)%loop==0:
        break

start = pos
if pos >= N:
    print(v)
else:
    res = []
    for i in range(start, N):
        if A[i] in res:
            res = res[:res.index(A[i])]
        else:
            res.append(A[i])

    print(*res)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, Counter
from bisect import bisect_right, bisect_left

N, K = map(int, input().split())
*A, = map(int, input().split())

c = Counter(A)
target = []
d = defaultdict(list)

dd = defaultdict(list)
for i, j in enumerate(A):
    dd[j].append(i)

pos = 0
loop = 1
l = []

while pos < N:
    num = A[pos]
    
    pp = bisect_right(dd[num], pos)
    if pp < len(dd[num]):
        pos = dd[num][bisect_right(dd[num], pos)]+1
    else:
        pos = dd[num][0]+1            
        loop += 1
    l.append((num, pos, loop))

for _, pos, p in l:
    if (K-p)%loop==0:
        break

start = pos
if pos >= N:
    print([])
else:
    res = []
    for i in range(start, N):
        if A[i] in res:
            res = res[:res.index(A[i])]
        else:
            res.append(A[i])

    print(*res)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_right
from collections import defaultdict

N, K = map(int, input().split())
As = list(map(int, input().split()))

indices_of_elem = defaultdict(list)
for i, A in enumerate(As):
    indices_of_elem[A].append(i)

empty_index = [0]
while True:
    cur_index = empty_index[-1]
    look_for_elem = As[cur_index%N]
    index_of_indices = bisect_right(indices_of_elem[look_for_elem], cur_index%N)
    if len(indices_of_elem[look_for_elem]) ==  index_of_indices:
        pair_end_index = (cur_index // N) * N + indices_of_elem[look_for_elem][0] + N
    else:
        pair_end_index = (cur_index // N) * N + indices_of_elem[look_for_elem][index_of_indices]

    new_index = pair_end_index + 1
    empty_index.append(new_index)
    if new_index % N == 0:
        break
loop = new_index // N

#print(loop, empty_index)

K %= loop

if K == 0:
    exit()
else:
    start = empty_index[bisect_right(empty_index, K * N) - 1] % N
    tmp_ans = As[start:]

#print(tmp_ans)

index_for_tmp_ans = dict()
split = []
for i, elem in enumerate(tmp_ans):
    if elem in index_for_tmp_ans:
        split.append((index_for_tmp_ans[elem], i))
        index_for_tmp_ans.pop(elem)
    else:
        index_for_tmp_ans[elem] = i

for start, end in split:
    tmp_ans[start:end+1] = [-1] * (end - start + 1)

for ans in tmp_ans:
    if ans != -1:
        print(ans, end = ' ')

Submission status: Wrong Answer

Solution code:
from bisect import bisect_right
from collections import defaultdict

N, K = map(int, input().split())
As = list(map(int, input().split()))

indices_of_elem = defaultdict(list)
for i, A in enumerate(As):
    indices_of_elem[A].append(i)

empty_index = [0]
while True:
    cur_index = empty_index[-1]
    look_for_elem = As[cur_index%N]
    index_of_indices = bisect_right(indices_of_elem[look_for_elem], cur_index%N)
    if len(indices_of_elem[look_for_elem]) ==  index_of_indices:
        pair_end_index = (cur_index // N) * N + indices_of_elem[look_for_elem][0] + N
    else:
        pair_end_index = (cur_index // N) * N + indices_of_elem[look_for_elem][index_of_indices]

    new_index = pair_end_index + 1
    empty_index.append(new_index)
    if new_index % N == 0:
        break
loop = new_index // N

#print(loop, empty_index)

K %= loop

start = empty_index[bisect_right(empty_index, K * N) - 1] % N
if start == 0:
    tmp_ans = []
else:
    tmp_ans = As[start:]

#print(tmp_ans)

index_for_tmp_ans = dict()
split = []
for i, elem in enumerate(tmp_ans):
    if elem in index_for_tmp_ans:
        split.append((index_for_tmp_ans[elem], i))
        index_for_tmp_ans.pop(elem)
    else:
        index_for_tmp_ans[elem] = i

for start, end in split:
    tmp_ans[start:end+1] = [-1] * (end - start + 1)

for ans in tmp_ans:
    if ans != -1:
        print(ans, end = ' ')

Submission status: Wrong Answer

Solution code:
from bisect import bisect_right
from collections import defaultdict

N, K = map(int, input().split())
As = list(map(int, input().split()))

indices_of_elem = defaultdict(list)
for i, A in enumerate(As):
    indices_of_elem[A].append(i)

empty_index = [0]
while True:
    cur_index = empty_index[-1]
    look_for_elem = As[cur_index%N]
    index_of_indices = bisect_right(indices_of_elem[look_for_elem], cur_index%N)
    if len(indices_of_elem[look_for_elem]) ==  index_of_indices:
        pair_end_index = (cur_index // N) * N + indices_of_elem[look_for_elem][0] + N
    else:
        pair_end_index = (cur_index // N) * N + indices_of_elem[look_for_elem][index_of_indices]

    new_index = pair_end_index + 1
    empty_index.append(new_index)
    if new_index % N == 0:
        break
loop = new_index // N

#print(loop, empty_index)

K %= loop

start = empty_index[bisect_right(empty_index, K * N) - 1] % N
tmp_ans = As[start:]

index_for_tmp_ans = dict()
split = []
for i, elem in enumerate(tmp_ans):
    if elem in index_for_tmp_ans:
        split.append((index_for_tmp_ans[elem], i))
        index_for_tmp_ans.pop(elem)
    else:
        index_for_tmp_ans[elem] = i

for start, end in split:
    tmp_ans[start:end+1] = [-1] * (end - start + 1)

for ans in tmp_ans:
    if ans != -1:
        print(ans, end = ' ')

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))


import bisect

n,k = readints()

a = readints()

place = [[] for i in range(max(a)+1)]

for i,x in enumerate(a):
    place[x].append(i)

now = 0
i = 1
while k>1:
    x = a[now]
    if now >= place[x][-1]:
        i+=1
        k-=1
        now = place[x][0]+1
    else:
        now = place[x][bisect.bisect_right(place[x],now)] + 1
    if now == n:
        now = 0
        k-=1
        k%=i
        if k<1:
            k+=i


ans = []
if now != 0:
    while now <= n-1:
        x = a[now]
        if now >= place[x][-1]:
            ans.append(x)
            now += 1
        else:
            now = place[x][bisect.bisect_right(place[x],now)] + 1

printline(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N,K=MI()
    A=LI()
    if N==1:
        if K%2==0:
            ans=[]
            print(' '.join(map(str, ans)))
        else:
            print(A[0])
    else:
        #有向グラフ
        #i番目からスタートした時，次の週のときにどこからスタートしたものと同様になるか，を追えば良い
        #例えば，12323ならば2週目の最初に1が出たときに実質リセットされるので2323をみるのと同じになる
        #これは結局，次に自分と同じ番号が出てくるところの次，なければループ
        M=2*(10**5)
        L=[[]for _ in range(M+1)]#各数字がどこに出てくるか記録
        
        A=A+A+A
        for i in range(N*3):
            L[A[i]].append(i)
            
        nxt=[0]*(N+1)
        
        import bisect
        for i in range(N-1,-1,-1):
            num=bisect.bisect_right(L[A[i]],i)
            nxt_st=L[A[i]][num]
            if nxt_st>=N:
                nxt[i]=nxt_st+1-N
            else:
                nxt[i]=nxt[(nxt_st+1)%N]
            # print(A[i])
            # print(L[A[i]])
            # print(num)
            # print(nxt_st)
            # print(nxt[i])
            # print("----")
            
        #nxtがわかればあとはダブリング
        N2=50
        dub=[[0]*(N+1) for _ in range(N2)]#最後に注意．1,2,3で3から始めたら次は無
        for i in range(N):#最後はどうせ０なので無視
            dub[0][i]=i
            dub[1][i]=nxt[i]

        
        for j in range(1,N2-1):
            for i in range(N):
                dub[j+1][i]=dub[j][dub[j][i]]
                
        # for j in range(10):
        #     print(dub[j])
        
        st=0
        K-=1#このdubやnxtは，次の時にどこから始まるかなので-1
        for j in range(1,N2):#0の時はいらない
            if K&1:
                st=dub[j][st]
            K=K>>1
            
        if st==N:
            ans=[]
            print(' '.join(map(str, ans)))
        else:

            
            ans=[]
            from collections import defaultdict
            dd = defaultdict(int)
            
            for i in range(st,N):
                if dd[A[i]]:
                    x=-1
                    while x!=A[i]:
                        x=ans.pop()
                        dd[x]=0
                else:
                    ans.append(A[i])
                    dd[A[i]]=1
                    
            print(' '.join(map(str, ans)))
        
    
    
    

main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N,K=MI()
    A=LI()
    if N==1:
        if K%2==0:
            print()
        else:
            print(A[0])
    else:
        #有向グラフ
        #i番目からスタートした時，次の週のときにどこからスタートしたものと同様になるか，を追えば良い
        #例えば，12323ならば2週目の最初に1が出たときに実質リセットされるので2323をみるのと同じになる
        #これは結局，次に自分と同じ番号が出てくるところの次，なければループ
        M=2*(10**5)
        L=[[]for _ in range(M+1)]#各数字がどこに出てくるか記録
        
        A=A+A+A
        for i in range(N*3):
            L[A[i]].append(i)
            
        nxt=[0]*(N+1)
        
        import bisect
        for i in range(N-1,-1,-1):
            num=bisect.bisect_right(L[A[i]],i)
            nxt_st=L[A[i]][num]
            if nxt_st>=N:
                nxt[i]=nxt_st+1-N
            else:
                nxt[i]=nxt[(nxt_st+1)%N]
            # print(A[i])
            # print(L[A[i]])
            # print(num)
            # print(nxt_st)
            # print(nxt[i])
            # print("----")
            
        #nxtがわかればあとはダブリング
        N2=50
        dub=[[0]*(N+1) for _ in range(N2)]#最後に注意．1,2,3で3から始めたら次は無
        for i in range(N):#最後はどうせ０なので無視
            dub[0][i]=i
            dub[1][i]=nxt[i]

        
        for j in range(1,N2-1):
            for i in range(N):
                dub[j+1][i]=dub[j][dub[j][i]]
                
        # for j in range(10):
        #     print(dub[j])
        
        st=0
        K-=1#このdubやnxtは，次の時にどこから始まるかなので-1
        for j in range(1,N2):#0の時はいらない
            if K&1:
                st=dub[j][st]
            K=K>>1
            
        if st==N:
            print()
        else:

            
            ans=[]
            from collections import defaultdict
            dd = defaultdict(int)
            
            for i in range(st,N):
                if dd[A[i]]:
                    x=-1
                    while x!=A[i]:
                        x=ans.pop()
                        dd[x]=0
                else:
                    ans.append(A[i])
                    dd[A[i]]=1
                    
            print(' '.join(map(str, ans)))
        
    
    
    

main()