[Question]
  [
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>
<https://www.youtube.com/watch?v=etMJxB-igrc>
<https://www.youtube.com/watch?v=8VrnqRU7BVU>
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.
Just the Nth term please.
Same (except for the seeing it already posted part), it seems code golfers and numberphile watchers have a decent overlap.
  
[Answer]
# JavaScript (ES6), ~~46 41~~ 37 bytes
```
n=>(g=p=>--n?g(g[p]-n|0,g[p]=n):p)(0)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3bbA1k5XN88@XSM9uiBWN6/GQAfEsM3TtCrQ1DDQ/J@cn1ecn5Oql5OfrpGmYaipqaCgr69gwIUqbgEVN0ITN7QESgDFTdHEjcwh4pZo4qZGEHETdIPMTCASBv8B "JavaScript (Node.js) – Try It Online")
### How?
We don't need to store the full sequence. We only need to keep track of the last position of each integer that appears in the sequence. We use the underlying object of the recursive function \$g\$ for that purpose.
For a given term \$p\$, we don't need either to set \$g[p]\$ to its actual absolute position in the sequence because we're only interested in the distance with the current position. That's why we can just store the current value of the input \$n\$, which is used as a decrementing counter in the code.
Therefore, the distance is given by \$g[p]-n\$. Conveniently, this evaluates to *NaN* if this is the first occurrence of \$p\$, which can be easily turned into the expected \$0\$.
### Commented
```
n => (           // n = input
  g = p =>       // g = recursive function taking p = previous term of the
                 //     sequence; g is also used as an object to store the
                 //     last position of each integer found in the sequence
    --n ?        // decrement n; if it's not equal to 0:
      g(         //   do a recursive call:
        g[p] - n //     subtract n from the last position of p
                 //     if g[p] is undefined, the above expression evaluates
        | 0,     //     to NaN, in which case we coerce it to 0 instead
        g[p] = n //     update g[p] to n
      )          //   end of recursive call
    :            // else:
      p          //   we've reached the requested term:
                 //   stop the recursion and return it
)(0)             // initial call to g with p = 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~69~~ ~~63~~ 62 bytes
```
f=lambda n,l=0,*s:f(n-1,l in s and~s.index(l),l,*s)if n else-l
```
[Try it online!](https://tio.run/##FcoxDsIwDAXQGU7h0UYpKrBV6mGCEoMl97dKOrRLr57Cm9@yr98Zr9Z09Di9UyQEH/twq4MyukdwMlCliHTUuyHljV2C/4KYEih7zZ03nQvZv5aIT@ZnL8P1shTDysom0k4 "Python 3 – Try It Online")
 Note: as Erik the Outgolfer mentioned, this code works fine in Python 2 as well. 
0-indexed (although, just to be utterly perverse, you can make it -1-indexed by changing `if n` to `if~n` :P)
Makes use of Python's gorgeous unpacking "star operator", to recursively build up the series, until `n` reaches zero.
The function builds up the series in the reverse order, to avoid having to reverse it for the search. Additionally, it actually stores the negations of all the elements, because converting them back at the end was free (else the `-` would have had to be a space) and it saves us a byte along the way, by using `~s.index(l)` instead of `-~s.index(l)`.
Could be 51 bytes if Python tuples had the same `find` functions strings do (returning -1 if not found, instead of raising an error), but no such luck...
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(n){while(sum(F|1)<n)F=c(match(F[1],F[-1],0),F)
+F[1]}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs7o8IzMnVaO4NFfDrcZQ0yZP0802WSM3sSQ5Q8Mt2jBWxy1aF0gaaOq4aXJpg0Rq/xcnFhTkVGoYWhka6KRp/gcA "R – Try It Online")
Builds the list in reverse; `match` returns the *first* index of `F[1]` (the previous value) in `F[-1]` (the remainder of the list), returning `0` if no match is found.
`F` is initialized to `FALSE` and is coerced to `0` on the first pass of the `while` loop.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~47~~ 42 bytes
*-5 bytes thanks to nwellnhof*
```
{({+grep(@_[*-1],:k,[R,] @_)[1]}...*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WqNaO70otUDDIT5aS9cwVscqWyc6SCdWwSFeM9owtlZPT09LM1olPrb2f3FipUKaRpyRgaY1F4QdbahjoWNoqWNkrmNqpGNmEhuha6j5HwA "Perl 6 – Try It Online")
Anonymous codeblock that outputs the 0-indexed element in the sequence.
### Explanation:
```
{                                            } # Anonymous codeblock
 (                                      )[$_]  # Return the nth element
                                    ...*       # Of the infinite sequence
  {                            }  # Where each element is
    grep(        :k        )[1]   # The key of the second occurrence
         @_[*-1],                 # Of the most recent element
                   ,[R,] @_       # In the reversed sequence so far
   +     # And numify the Nil to 0 if the element is not found
```
[Answer]
# Bourne shell, 102 bytes
```
until [ 0"$i" -eq $1 ];do i=$((${i:-0}+1)) a=${n:-0};eval 'n=$(($i-${m'$a:-$i'}))' m$a=$i;done;echo $a
```
[try it online](https://tio.run/##HcxNCoMwFEXhrVzkQgwloIITgysRB69twAcaKf2ZBNf@ajs88HGu8lzM3vmlKyY0FbVCSA@wxRzvO3RkXbPoEJrj0noPGVnyr2L6yAqX/0ADy@YoQ6C6w3uHjafUc5FTTLdlB8XM@u4L)
[Answer]
# [Python](https://docs.python.org/2/), 51 bytes
```
f=lambda n,i=1:n>i and[f(n,i+1),i][f(n-1)==f(n+~i)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n09bQKs8uUyExLyU6TQPI1zbU1MmMBbF1DTVtbYG0dl2mZuz/tPwihTyFzDyFosS89FQNQ0NNKy6FgqLMvBKgKQraQHWa/wE "Python 2 – Try It Online")
Outputs `False` for `0`. Implements the spec pretty literally, looking for the lowest positive integer `i` such that `f(n-1)==f(n-i-1)`. If such a search leads to `i>=n`, the previous element hasn't appeared before and we produce `0`.
Instead of doing something reasonable like storing earlier values in a list, the function just recomputes them recursively from scratch whenever they're needed, and sometimes when they're not needed. This makes the function run very slowly for inputs above 10 or so.
[Answer]
# [J](http://jsoftware.com/), ~~29~~ 23 bytes
```
1{(,~#|1+}.i.{.)@]^:[&0
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Das1dOqUawy1a/Uy9ar1NB1i46yi1Qz@a3KlJmfkAxXaKqQpGEI4RmCOBYRjCpGxhPAswTwjcwjPBKLS1AjZEDOT/wA "J – Try It Online")
The real work is done in the iteration verb of the power verb `^:`, which iterates as many times as the argument `[`, starting the iteration with the constant value 0 `&0`...
* `(#|1+}.i.{.)` This is what iterates. Breaking it down...
* `}.i.{.` Find the index of `i.` of the head of the list `{.` within the tail of the list `}.`. This will return a 0-based index, so if the current item is found 1 previous it will return 0. If it is not found, it will return the length of the list, ie, the length of the tail.
* `1+` Add one to the value to correct for the 0-based indexing, since the Ven Eck's "how far back" is 1-based. Note that if it was not found, the value will now be the length of the full list.
* `#|` Return the remainder of the value calculated in the previous step, when divided by the length of the full list. Note that this turns "not found" into 0, but leaves all other values unchanged.
* `,~` Append the new value to the front of the list. We use the front rather than last merely for convenience.
* `1{` return the 2nd item in the list, since we calculated one too many times because it's shorter that way.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~10~~ 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é"▬π²"ô↕j
```
[Run and debug it](https://staxlang.xyz/#p=822216e3fd2293126a&i=1%0A8%0A19%0A27%0A52%0A64&a=1&m=2)
If 0-based indexing is allowed:
### [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
à┐æ8Å/[┤
```
[Run and debug it](https://staxlang.xyz/#p=85bf91388f2f5bb4&i=0%0A7%0A18%0A26%0A51%0A63&a=1&m=2)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
#<1||Last[#-1-Array[#0,#-2]~Position~#0[#-1],0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9nGsKbGJ7G4JFpZ11DXsagosTJa2UBHWdcoti4gvzizJDM/r07ZACQbq2MQq/Y/sDQztSQ6oCgzD6TFLs1BOVZN3yEoMS891cHQIPY/AA "Wolfram Language (Mathematica) – Try It Online")
Nonzero values are [returned as singleton lists](https://codegolf.meta.stackexchange.com/a/11884/81203).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Many thanks to ngn, Adám, Richard Park and H.PWiz for their help in writing and golfing this answer in [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard), a great place to learn APL and get APL help.
**Edit:** -2 bytes from Adám.
```
⊃(⊢,⍨≢|1∘↓⍳⊃)⍣⎕-1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe3/o65mjUddi3Qe9a541LmoxvBRx4xHbZMf9W4GSmg@6l38qG@qriFILVfao7YJj3r7DB/17FWvrVbXUQdKgXCR@qPerepAM4we9WwH8pOL1NPUFR71zlUoKUpMSctTKMlXAFL/q4HKFAwf9W4BMXTSgETtoRUgi4AMQwMDAA "APL (Dyalog Unicode) – Try It Online")
**Explanation**
```
⊃(⊢,⍨≢|1∘↓⍳⊃)⍣⎕-1
                 -1  We initialize our array of results with -1.
 (           )⍣⎕    ⍣ repeats the train (in parentheses) our input, ⎕, times.
        1∘↓⍳⊃        We take the index of the head (our last element in the sequence).
                     To signify "element not found", this returns the length of the array.
      ≢|             We take our index modulo the length of the array.
                     This turns our "element not found" from the length of the array to 0.
  ⊢,⍨                And we prepend to our array.
⊃                    Finally, we return the first element of the array,
                     which is the most recently-generated.
                     This is the ⍵-th element of the Van Eck sequence.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
F¯Rćk>Dˆ
```
[Try it online](https://tio.run/##yy9OTMpM/f/f7dD6oCPt2XYup9v@/zc1AgA) or [output the first \$n\$ values in the list](https://tio.run/##yy9OTMpM/f/f7dD6oCPt2Xan22oPrf//39DAAAA).
**Explanation:**
```
F         # Loop the (implicit) input amount of times:
 ¯        #  Push the global array
  R       #  Reverse it
   ć      #  Extract the head; push the remainder and the head to the stack
    k     #  Get the 0-based index of the head in the remainder (-1 if not found)
     >    #  Increase it by 1 to make it 1-indexed (or 0 if not found)
      Dˆ  #  Add a copy to the global array
          # (after the loop, output the top of the stack implicitly as result,
          #  which is why we need the `D`/duplicate)
```
[Answer]
## Java, 96 80 76 bytes
```
n->{int i,v=0,m[]=new int[n];for(;--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;}
```
Not obfuscated:
```
Function<Integer, Integer> vanEck =
n -> {
    int i;                  // i is the value of n when v was previously encountered
    int v = 0;              // v is the current element of vanEck sequence
    int[] m = new int[n];   // m[v] is the value of n when v was previously encountered
    while (--n > 0) {       // n is used as a decrementing counter
        i = m[v];
        m[v] = n;
        v = i == 0 ? 0 : i - n;
    }
    return v;
};
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ḷß€ṚiḢ$
```
[Try it online!](https://tio.run/##y0rNyan8///hjm2H5z9qWvNw56zMhzsWqfw3NAEJtQOF/gMA "Jelly – Try It Online")
0-indexed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
≔⁰θＦ⊖Ｎ«≔⊕⌕⮌υθη⊞υθ≔ηθ»Ｉθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEehUNOaKy2/SEHDJTW5KDU3Na8kNUXDM6@gtMSvNDcptUhDU1NToZqLE6rDMw@hyi0zL0UjKLUstag4VaNUE2QWkMgAGsgZUFqcoVEKMR2mNQPCreUKKMrMK9FwTiwu0QDqsP7/39Dyv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰θ
```
Set the first term to 0.
```
Ｆ⊖Ｎ«
```
Loop `n-1` times. (If 0-indexing is acceptable, the `⊖` can be removed for a 1-byte saving.)
```
≔⊕⌕⮌υθη
```
The next term is the incremented index of the current term in the reversed list of previous terms.
```
⊞υθ
```
Add the current term to the list of previous terms.
```
≔ηθ
```
Set the current term to the next term.
```
»Ｉθ
```
Print the current term at the end of the loop.
[Answer]
# Perl 5 (`-p`), 42 bytes
```
map{($\,$\{$\})=0|$\{$\};$_++for%\}1..$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaQyVGRyWmWiWmVtPWoAbCslaJ19ZOyy9Sjak11NNTia@t/v/f1OhffkFJZn5e8X/dAgA "Perl 5 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes
```
!¡oΓ€↔ø
```
[Try it online!](https://tio.run/##ATAAz/9odXNr/21vd1Ms4oKB/yHCoW/Ok@KCrOKGlMO4////WzEsOCwxOSwyNyw1Miw2NF0 "Husk – Try It Online") The behavior of `€` is surprisingly helpful here.
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f n=last$0:[n-j-1|j<-[0..n-2],f j==f(n-1)]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYnsbhExcAqOk83S9ewJstGN9pATy9P1yhWJ00hy9Y2TSNP11Az9n9uYmaegq1CQVFmXomCikKago2KnQJIqaFB7H8A "Haskell – Try It Online")
Other Haskell answers: [66 bytes by flawr](https://codegolf.stackexchange.com/a/186680/3852) and [61 bytes by nimi](https://codegolf.stackexchange.com/a/186707/3852).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẎiḢ$;µ¡Ḣ
```
A monadic Link accepting a positive integer, \$n\$, which yields the \$n^{th}\$ term of the Van Eck Sequence.
**[Try it online!](https://tio.run/##y0rNyan8///hrr7MhzsWqVgf2npoIZDx//9/UyMA "Jelly – Try It Online")**
### How?
```
ẎiḢ$;µ¡Ḣ - Link: n
     µ¡  - repeat this monadic link n times - i.e. f(f(...f(n)...)):
         - (call the current argument L)
Ẏ        -   tighten (ensures we have a copy of L, so that Ḣ doesn't alter it)
   $     -   last two links as a monad:
  Ḣ      -     head (pop off & yield leftmost of the copy)
 i       -     first index (of that in the rest) or 0 if not found
    ;    -   concatenate with L
       Ḣ - head
```
Note that without the final `Ḣ` we've actually collected `[a(n), a(n-1), ..., a(2), a(1), n]`
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
```
f(n){n=g(n,--n);}g(n,i){n=n>0?f(--n)-f(i)?g(n,i)+!!g(n,i):1:0;}
```
[Try it online!](https://tio.run/##JcwxCsMwDIXh3adwAgEJW@CMjZrkIl2Kg4KGqiV0Cz67W5Pt53vwMu051ypgeNq8g0UiQy6ttJEtaRVoSAKK6zWErrtiGqfEpb6eaoCnk/cBal@vc2K9jzfWENB9jr8J9MPmafHD9rA@amx3yK7UHw "C (gcc) – Try It Online")
0-indexed.
[Answer]
# [Haskell](https://www.haskell.org/), ~~68 67~~ 66 bytes
Quite straightforward implementation (using 0 based indexing).
```
f n|all((/=f(n-1)).f)[0..n-2]=0|m<-n-1=[k|k<-[1..],f(m-k)==f m]!!0
```
[Try it online!](https://tio.run/##FcwxDsMgDADArxgpA0i1A5lxP4IYGGIFAVbVduTvpF1vuKt82tn7WgI6S@/W7ixWMThH4pInUjwy@zki/pRTmy1iCkT5IXZgc8wCIxvj1yhVgeH1rvqFDQTi9oR/EXxeNw "Haskell – Try It Online")
[Answer]
## Haskell, 61 bytes
```
(([]#0)1!!)
(l#n)i=n:(((n,i):l)#maybe 0(i-)(lookup n l))(i+1)
```
0-based indexing.
[Try it online!](https://tio.run/##BcHBDoIwDADQu19RMg9tFLIdvJDsS4DDJEwburKAHPx563vvdKyLiOU4GuIwOU@haeiC4pQ4ao@IemfqhVxJ3@cCHrkllG1bzwoKQoR8C2QlsUKEurN@4AolVcgw@K4Lj8l@c5b0Oqyda/0D "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 11 bytes
```
@ÒZÔÅbX}hTo
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=QNJa1MViWH1oVG8&input=NTI)
[Answer]
## CJam (15 bytes)
```
0a{_(#)\+}qi*0=
```
[Online demo](http://cjam.aditsu.net/#code=0a%7B_(%23)%5C%2B%7Dqi*0%3D&input=9). This is a full program and 0-indexed.
### Dissection
```
0a      e# Push the array [0]
{       e# Loop...
  _(#   e#   Copy the array, pop the first element, and find its index in the array
  )\+   e#   Increment and prepend
}qi*    e# ... n times, where n is read from stdin
0=      e# Take the first element of the array
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 77 bytes
```
n=>{int i,v=0;for(var m=new int[n];--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;}
```
[Try it online!](https://tio.run/##HYyxCsMwDAV3f4VGm8TgrFXkbp27hwzFxKAhKjiJM5R@u6t0ePA4jkubTxu3xyFpZNl7XczUhOJHL3BfKWB@F1tfBVaS5QTlk8zovcSA61RnErV4HO7hxl4c0wWxLPtRBCp@GxpzJf5BGlDVEJC7zhmAZ1Fss2XnsP0A "C# (Visual C# Interactive Compiler) – Try It Online")
Pretty much a port of the Java answer at this point.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~128~~ ~~114~~ ~~111~~ ~~102~~ 99 bytes
*102 -> 99 bytes, thanks to Jonathan Frech*
```
f=lambda n,i=1,l=[0]:f(n,i+1,l+[l[i-2::-1].index(l[-1])+1if l[-1]in l[:-1]else 0])if n>i else l[-1]
```
[Try it online!](https://tio.run/##RcpNCsIwEAXgvaeYXROaShP7D/UiIYtKExyIsWgXCt49xirjat773izP9XwNhxjd6KfLaZ4gCByl8KMuzeBYanlqufYaCzUMhTR7DLN9MK9T5rlEB1vEkO5nt/5uoTQ8DeGIsNXtIy43DCuTAjJ4ZQIck5zvvtj9sSOUfdLfZ0@qWlLVktaKtFakTUXaVJzHNw "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
W?(p:ḣḟ›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiVz8ocDrhuKPhuJ/igLoiLCIiLCIxXG44XG4xOVxuMjdcbjUyXG42NCJd) 1-indexed.
**Explanation:**
Since \$a(n) < n\$, we can push \$n\$ to the beginning of the list. Also builds the sequence backwards.
```
W?(p:ḣḟ› # whole program
W        # []
 ?       #            input
  (      # repeat for       times:
   p     #  prepend to list (uses implicit input the first time)
    :    #  duplicate
     ḣ   #  split head from the rest
      ḟ  #  find its index on the list (-1 if none)
       › #  increment
         # as we didn't prepend the last item, output it 
```
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes
```
a=[0]
for _ in a*int(input()):k=a[-1];a+=k in a[:-1]and[a[::-1].index(k)+~a[-2::-1].index(k)]or[0]
print(-a[-2])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9E22iCWKy2/SCFeITNPIVErM69EIzOvoLREQ1PTKts2MVrXMNY6Uds2GywdbQXkJualRANZIKZeZl5KaoVGtqZ2HVClEapYbH4RyPCCIpCZuiD5WM3//43MAQ "Python 3 – Try It Online")
-3 bytes thanks to mypetlion
[Answer]
# [Red](http://www.red-lang.org), ~~106~~ 95 bytes
```
func[n][b: copy[0]loop n[insert b either not find t: next b
b/1[0][-1 + index? find t b/1]]b/2]
```
[Try it online!](https://tio.run/##Pcu7DgIhFIThfp9iemNWiFca38H2hIblEEnMgbCYrE@PFEr3Jf9MYd8e7MlOwbTwloXEkjNYUv7Qwb5SyhCKsnKpcOBYn1wgqSJE8agGwlsvk5tV39NeYYdeeLv/FujFWjdr23KJ0o9Q01/XIXUb1JfBkx48H9sX "Red – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
VQ=Y+?YhxtYhY0Y;hY
```
[Try it online!](https://tio.run/##K6gsyfj/PyzQNlLbPjKjoiQyI9Ig0joj8v9/UyMA "Pyth – Try It Online")
Builds up the sequence in reverse and prints the first element (last term of the sequence).
```
VQ                 # for N in range(Q) (Q=input)
  =Y+         Y    # Y.prepend(
        xtY        #   Y[1:].index(    )
           hY      #               Y[0]
       h           #                     +1
     ?Y      0     #                        if Y else 0)
               ;hY # end for loop and print Y[0]
```
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn) `-f`, [13 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
f→S›J⁻åƒƒN5═%
```
[Try it!](https://zippymagician.github.io/Arn?code=Ji57KysuezppOnspfH1b&input=MQo4CjE5CjI3CjUyCjY0&flags=Zg==)
0-indexed
# Explained
Unpacked: `&.{++.{:i:{)|}[`
```
&.            Mutate S N times
  {             With block, key of `_`
      ++        Increment
            _   Implicit
          .{    Behead
        :i      Index of
            _   Implicit
          :{    Head
      )     Don't ask
    |           Concatenated with
      _         Implicit
  }             End block
  [           Where S is an array
  ]             Ending implicit
  _           And N is STDIN; implicit
            Then take the head
```
]