Nth term of Van Eck Sequence

Output the Nth term of the Van Eck Sequence.

Van Eck Sequence is defined as:

• Starts with 0.
• If the last term is the first occurrence of that term the next term is 0.
• If the last term has occurred previously the next term is how many steps back was the most recent occurrence.

https://oeis.org/A181391

Sequence: 0,0,1,0,2,0,2,2,1,6,0,5,0,2,...

Tests:

Input | Output

• 1 | 0
• 8 | 2
• 19 | 5
• 27 | 9
• 52 | 42
• 64 | 0

EDIT

1 indexed is preferred, 0 indexed is acceptable; that might change some of the already submitted solutions.

Same (except for the seeing it already posted part), it seems code golfers and numberphile watchers have a decent overlap.

• Watched the numpherphile video at work and was going to post this when I got home. Curse you for getting there first. :P Jun 10 '19 at 21:27
• Does it have to be 1-indexed, or may we use 0-indexing? Jun 10 '19 at 22:02
• May we return or output the infinite sequence instead?
– Jo King
Jun 11 '19 at 2:10
• ... or the first n terms? Jun 11 '19 at 15:11
• @Draco18s The same thing happened to me. :P Jul 5 '19 at 16:31

DC, 94 91 90 bytes

Input is taken during the program. Save this to a file and then do "dc " to run. Definitely not the shortest, but I have fun with challenges like these in dc. Input is 1-based index, as preferred.

[st1si0swlbxltlwlu1-sulu0!=m]sm[dlt=qSsli1+siz0!=b0siLs]sb[0pq]sf[lisw2Q]sq?2-dsu1>f0dlmxp

Main control macro
[st                         ]sm   save top value as target
[  1si0sw                   ]sm   reset i to 1 and w to 0
[        lbx                ]sm   execute macro b to get next value in w
[           ltlw            ]sm   restore target to the stack and add w to the stack
[               lu1-su      ]sm   decrement the user inputted variable
[                     lu0!=m]sm   if the user inputted variable is not 0 recurse

Next value finder macro
[dlt=q                  ]sb     if the value on the stack is the target, quit
[     Ss                ]sb     save top value to s register
[       li1+si          ]sb     increment i register
[             z0!=b     ]sb     recurse if still more values
[                  0si  ]sb     set i to 0 (will be saved to w if relevant)
[                     Ls]sb     move top value of s register to stack

[lisw2Q]sq   Load i, save it to w, and then quit this macro and the one that called it

[0pq]sf print 0 and quit the program
$$$$


C++ (clang), 241235234219197 189 bytes

197 -> 189 bytes, thanks to ceilingcat

#import<bits/stdc++.h>
int f(int n,int i=0,std::vector<int>l={0}){return~-n>i?l.push_back(find(begin(l),end(l)-1,l[i])-end(l)+1?find(rbegin(l)+1,rend(l),l[i])-rbegin(l):0),f(n,i+1,l):l[i];}
`

Try it online!