The only difference between easy and hard versions are constraints on $n$ and $k$.

You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$).

Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.

You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$).

If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.

Otherwise (i.e. if there is no conversation with $id_i$ on the screen):

  Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen.  The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. 

Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.


-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 2 \cdot 10^5)$ — the number of messages and the number of conversations your smartphone can show.

The second line of the input contains $n$ integers $id_1, id_2, \dots, id_n$ ($1 \le id_i \le 10^9$), where $id_i$ is the ID of the friend which sends you the $i$-th message.


-----Output-----

In the first line of the output print one integer $m$ ($1 \le m \le min(n, k)$) — the number of conversations shown after receiving all $n$ messages.

In the second line print $m$ integers $ids_1, ids_2, \dots, ids_m$, where $ids_i$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $i$ after receiving all $n$ messages.


-----Examples-----
Input
7 2
1 2 3 2 1 3 2

Output
2
2 1 

Input
10 4
2 3 3 1 1 2 1 2 3 3

Output
3
1 3 2 



-----Note-----

In the first example the list of conversations will change in the following way (in order from the first to last message):

  $[]$;  $[1]$;  $[2, 1]$;  $[3, 2]$;  $[3, 2]$;  $[1, 3]$;  $[1, 3]$;  $[2, 1]$. 

In the second example the list of conversations will change in the following way:

  $[]$;  $[2]$;  $[3, 2]$;  $[3, 2]$;  $[1, 3, 2]$;  and then the list will not change till the end.

Difficulty: introductory

Starter code:

Solutions:
from collections import deque
n, k = map(int, input().split())
A = list(map(int, input().split()))
B = deque()
B.append(A[0])
nc = {}
for i in set(A):
    nc[i] = 0
nc[A[0]] = 1
for i in range(1, n):
    if nc[A[i]] == 0:
        if len(B) == k:
            nc[B[0]] -= 1
            B.popleft()
        B.append(A[i])
        nc[A[i]] += 1
    else:
        pass
print(len(B))
print(*list(B)[::-1])

n, k = map(int, input().split())
a = map(int, input().split())

lt = dict()
timer = 0
for Id in a :
    if Id not in lt :
        lt[Id] = -k
    cur_time = lt[Id]
    if cur_time <= timer - k :
        timer += 1
        lt[Id] = timer
    
screen = list(lt.items())
screen.sort(key=(lambda t: -t[1]))
# print(screen)
screen = screen[:min(n, k)]
print(len(screen))
for v in screen :
    print(v[0], end=' ')
print()


from collections import deque
a, b = map(int, input().split())
li = list(map(int, input().split()))
s = set()
l = deque([])
le = 0
for i in li:
    if i in s:
        pass
    elif le < b:
        le += 1
        s.add(i)
        l.appendleft(i)
    else:
        s.remove(l.pop())
        s.add(i)
        l.appendleft(i)       
print(len(l))
print(*list(l))

from collections import deque
n,k=map(int,input().split())
d=deque()
s=set()
for i in map(int,input().split()):
  if i in s:continue
  d.appendleft(i);s.add(i)
  if len(d)>k:s.discard(d.pop())
print(len(d))
print(*d)

import sys
input = sys.stdin.readline

n,k=list(map(int,input().split()))
A=list(map(int,input().split()))

SET=set()

from collections import deque

Q=deque()

for a in A:
    if a in SET:
        continue
    else:
        if len(Q)==k:
            x=Q.pop()
            SET.remove(x)
            Q.appendleft(a)
            SET.add(a)
        else:
            SET.add(a)
            Q.appendleft(a)

print(len(Q))
print(*Q)
            
            


import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
# print = stdout.write
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())

n, k = mapin()
a = listin()
s = set([])
d = deque([])
for i in a:
    if len(d) < k:
        if i not in s:
            s.add(i)
            d.append(i)
    else:
        if i not in s:
            s.remove(d.popleft())
            d.append(i)
            s.add(i)
print(len(d))
d = list(d)
d.reverse()
print(*d)

import heapq
import math

import sys
input = sys.stdin.readline

def li():return [int(i) for i in input().rstrip('\n').split()]
def value():return int(input())

n,k = li()
a = li()

curr = []
currd = {}
currd2 = {}
for i in range(n):
    if a[i] not in currd2:
        if len(curr) == k:
            
            currd2.pop(currd.pop(heapq.heappop(curr)))
        heapq.heappush(curr,i)
        currd[i] = a[i]
        currd2[a[i]] = i
curr.sort(reverse = 1)
ans = []
for i in curr:
    ans.append(currd[i])
print(len(ans))
print(*ans)

n, k = map(int, input().split())
a = [*map(int, input().split())]

from collections import deque

ans = deque()
ins = set()

for i in a:
	if i not in ins:
		if len(ans) == k:
			ins.remove(ans[0])
			ans.popleft()
		ans.append(i)
		ins.add(i)

ans.reverse()

print(len(ans))

print(*ans)

from collections import deque
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
now = set()
letters = deque()
for i in range(n):
    if a[i] not in now:
        now.add(a[i])
        if len(letters) < k:
            letters.append(a[i])
        else:
            now.remove(letters.popleft())
            letters.append(a[i])
print(len(letters))
print(*list(letters)[::-1])

from collections import deque
n, k = list(map(int,input().split()))

q = deque()
a = list(map(int, input().split()))
vis = set()

for i in range(n):
    if len(q) < k:
        if a[i] not in vis:
            q.append(a[i])
            vis.add(a[i])
    else:
        if a[i] not in vis:
            q.append(a[i])
            vis.remove(q.popleft())
            vis.add(a[i])

print(len(q))
print(str(list(q)[::-1]).replace('[','').replace(']','').replace(', ',' '))


from collections import OrderedDict
class LRUCache:

    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = OrderedDict()

    def set(self, key, value):
        if len(self.cache) == self.capacity:
            self.cache.popitem(last=False)
        self.cache[key] = value

n, k = map(int, input().strip().split())
ids = map(int, input().strip().split())
convs = LRUCache(k)
for i in ids:
    if i in convs.cache:
        continue
    else:
        convs.set(i, None)
print(len(convs.cache))
print(" ".join(map(str, reversed(convs.cache.keys()))))

from collections import defaultdict as df
import heapq
import bisect 
import math
from itertools import combinations,permutations
from collections import deque

n,k=list(map(int,input().split()))
a=list(map(int,input().rstrip().split()))
ans=deque()
p=df(int)
for i in range(n):
    p[i]=0
for i in a:
    if p[i]>0:
        pass
    
    else:
        if len(ans)>=k:
            g=ans.pop()
            ans.appendleft(i)
            p[i]+=1
            p[g]-=1
        else:
            ans.appendleft(i)
            p[i]+=1
print(len(ans))
print(*ans)

a=list(map(int,input().split()))
sc=a[1]
m=a[0]
a=list(map(int,input().split()))
d={}
s=[]
for i in a:
    if i in d: continue
    if len(s)<sc: 
        s.append(i)
        d[i]=1
    else:
        d.pop(s.pop(0))
        s.append(i)
        d[i]=1
print(len(s))
print(*s[::-1])

'''input
10 4
2 3 3 1 1 2 1 2 3 3
'''
from sys import stdin
from collections import deque
import math


# main starts
n, k = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
myq = deque([])
myset = set()
for i in range(n):
	if arr[i] in myset:
		pass
	else:
		if len(myq) == k:
			el = myq[-1]
			myset.remove(el)
			myq.pop()
		myq.appendleft(arr[i])
		myset.add(arr[i])

print(len(myq))

print(*myq)

from collections import deque
n, k = list(map(int, input().split()))
s = set()
d = deque()
for i in map(int, input().split()):
    if i in s:
        continue
    if len(d) == k:
        s.discard(d.pop())
    d.appendleft(i)
    s.add(i)
print(len(d))
print(*d)


from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
    for i in range(2,MAXN,2):
        spf[i] = 2
    for i in range(3,int(MAXN**0.5)+1):
        if spf[i]==i:
            for j in range(i*i,MAXN,i):
                if spf[j]==j:
                    spf[j]=i
def fib(n,m):
    if n == 0:
        return [0, 1]
    else:
        a, b = fib(n // 2)
        c = ((a%m) * ((b%m) * 2 - (a%m)))%m
        d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m
        if n % 2 == 0:
            return [c, d]
        else:
            return [d, c + d]

def charIN(x= ' '):
    return(sys.stdin.readline().strip().split(x))

def arrIN(x = ' '):
    return list(map(int,sys.stdin.readline().strip().split(x)))

def ncr(n,r):
    num=den=1
    for i in range(r):
        num = (num*(n-i))%MOD
        den = (den*(i+1))%MOD

    return (num*(pow(den,MOD-2,MOD)))%MOD

def flush():
    return sys.stdout.flush()

'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''

n,k = arrIN()
a = arrIN()
st = []
ls = 0
f = defaultdict(int)
j = 0
for i in a:
    if f[i]==0:
        if ls<k:
            st.append(i)
            f[i] = 1
            ls+=1
        else:
            f[st[j]] = 0
            j+=1
            st.append(i)
            f[i] = 1
    #print(st)
print(len(st)-j)
for i in range(len(st)-1,j-1,-1):
    print(st[i],end=' ')


import sys
from collections import deque, defaultdict

# stdin = open("testdata.txt", "r")
n, k = map(int, sys.stdin.readline().split())

a = list(map(int, sys.stdin.readline().split()))
dq = deque()
on_dq = defaultdict(int)
length = 0
for ele in a:
	if not on_dq[ele]:
		on_dq[ele] = 1
		length += 1
		dq.appendleft(ele)
		if length > k:
			item = dq.pop()
			on_dq[item] = 0
			length -= 1
print(length)
print(*dq)

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

from collections import deque

que = deque()
used = set()

for id in id_list:
    if id in used:
        continue
    else:
        if len(que) >= K:
            q = que.pop()
            used.remove(q)
        que.appendleft(id)
        used.add(id)

print(len(que))
while len(que) != 0:
      print(que.popleft(), end=" ")


# -*- coding: utf-8 -*-

import sys
from collections import deque

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return list(map(int, input().split()))
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
A = LIST()

que = deque()
S = set()
for a in A:
    if len(que) < K:
        if a not in S:
            que.appendleft(a)
            S.add(a)
    else:
        if a not in S:
            b = que.pop()
            S.remove(b)
            que.appendleft(a)
            S.add(a)
print(len(que))
print(*que)


n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
from collections import deque
from collections import defaultdict
b = deque()
c = defaultdict(int)
for i in a:
    c[i]=0
l = 0
i = 0
while i<n:
    if l<k:
        if c[a[i]]==1:
            i=i+1
            continue
        else:
            b.appendleft(a[i])
            c[a[i]]=1
            l=l+1
            i=i+1
    else:
        if c[a[i]]==1:
            i=i+1
            continue
        else:
            e=b.pop()
            c[e]=0
            c[a[i]]=1
            b.appendleft(a[i])
            i=i+1
print(len(b))
print(*b)


from queue import Queue

def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))

    checked = {}
    for a in A:
        checked[a] = False

    q = Queue()
    for i, a in enumerate(A):
        if checked[a]:
            continue
        else:
            checked[a] = True
            q.put(a)
            if q.qsize() > K:
                b = q.get()
                checked[b] = False
    L = q.qsize()
    ans = []
    for i in range(L):
        a = q.get()
        ans.append(a)
    print(L)
    print(' '.join([str(a) for a in ans[::-1]]))

def __starting_point():
    main()
__starting_point()