[Question]
  [
Given a list of integers, your task is to output the second largest value in the first *k* elements, for each *k* between 2 and the length of the input list.
In other words, output the second largest value for each prefix of the input.
You can output an arbitrary value for the first element (where *k* = 1), or simply omit this value, as there isn't a second maximum for a list of 1 element. You may assume there are at least 2 elements in the input.
Shortest code wins.
## Examples
```
Input:
1 5 2 3 5 9 5 8
Output:
  1 2 3 5 5 5 8
Input:
1 1 2 2 3 3 4
Output:
  1 1 2 2 3 3
Input:
2 1 0 -1 0 1 2
Output:
  1 1 1 1 1 2
```
  
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
ηεà\à
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3PZzWw8viDm84P//aEMdBVMdBSMdBWMwwxJMWsQCAA "05AB1E – Try It Online")
Returns `[]` (arbitrary value) for first.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 7 bytes
Saved a byte or two thanks to @Zgarb
```
mȯ→hOtḣ
```
Returns `0` for the first "second maximum"
### Explaination
```
         -- implicit input, e.g          [1,5,3,6]
      ḣ  -- prefixes                     [[],[1],[1,5],[1,5,3],[1,5,3,6]]
     t   -- remove the first element     [[1],[1,5],[1,5,3],[1,5,3,6]]
mȯ       -- map the composition of 3 functions
    O    --   sort                       [[1],[1,5],[1,3,5],[1,3,5,6]]
   h     --   drop the last element      [[],[1],[1,3],[1,3,5]
  →      --   return the last element    [0,1,3,5]
         -- implicit output
```
[Try it online!](https://tio.run/##yygtzv7/P/fE@kdtkzL8Sx7uWPz///9oQx1THSMdYyBpCcQWsQA "Husk – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
lambda x:[sorted(x[:i])[-2]for i in range(2,1+len(x))]
```
[Try it online!](https://tio.run/##HYtBDsIgEEX3noJdIU4ToZooiSehLDAFJcGhQRZ4ehxczM//72X2b31lVD3c157c@7E51rT55FL9xpvR0QozKxtyYZFFZMXh03MF8pg88iaE7cOl4YyRcAEFC@WN7mqBiCQy2AJn2vQJJ5hHkLBWH9heIlaWYFpxgsCT@Lfefw "Python 2 – Try It Online")
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
poil
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FksK8jNzlhQnJRdDBRbcNIo21DHVMdIxBpKWQGwRywUUMQSKgMSMdUyAfCMg30BHF0QAJWIhWgE)
```
p     Prefix
 o    Sort
  i   Init (remove the last element)
   l  Last
```
Accidentally, [poil means hair in French](https://en.wiktionary.org/wiki/poil).
[Answer]
## JavaScript (ES6), ~~58~~ ~~51~~ 50 bytes
*Saved 1 byte thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
Appends `undefined` for ***k = 1***.
```
a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[])
```
### Test cases
*NB: This snippet uses `JSON.stringify()` for readability, which -- as a side effect -- converts `undefined` to `null`.*
```
let f =
a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[])
console.log(JSON.stringify(f([1, 5, 2, 3, 5, 9, 5, 8]))) // 1 2 3 5 5 5 8
console.log(JSON.stringify(f([1, 1, 2, 2, 3, 3, 4])))    // 1 1 2 2 3 3
console.log(JSON.stringify(f([2, 1, 0, -1, 0, 1, 2])))   // 1 1 1 1 1 2
```
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
f=lambda l:l[1:]and f(l[:-1])+[sorted(l)[-2]]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIccqJ9rQKjYxL0UhTSMn2krXMFZTO7o4v6gkNUUjRzNa1yg29n9BUWZeCVA@2lDHVMdIxxhIWgKxRawmF5KUIVAKJGmsY4IsYQSUMNDRBRFAFbGa/wE "Python 2 – Try It Online")
The right side of the code is self-explanatory. However, what do we put to the left of the `and`? Because we are concatenating parts of a list recursively, we need the left side to be truthy if `l` has 2 or more elements, and an empty list otherwise. `l[1:]` satisfies this criterion nicely. 
[Answer]
# [Pyth](https://pyth.readthedocs.io), 8 bytes
```
m@Sd_2._
```
**[Try it online!](https://pyth.herokuapp.com/?code=m%40Sd_2._&input=%5B1%2C5%2C2%2C3%2C5%2C9%2C5%2C8%5D&debug=0)** or **[Try the Test Suite!](http://pyth.herokuapp.com/?code=m%40Sd_2._&input=%5B1%2C+5%2C+2%2C+3%2C+5%2C+9%2C+5%2C+8%5D&test_suite=1&test_suite_input=%5B1%2C5%2C2%2C3%2C5%2C9%2C5%2C8%5D%0A%5B1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+4%5D%0A%5B2%2C+1%2C+0%2C+-1%2C+0%2C+1%2C+2%5D&debug=0)**
---
# How?
This outputs the first element of the list as the first value in the list, as per the spec *You can output an arbitrary value for the first element*.
```
m@Sd_2._   - Full program with implicit input.
m     ._Q  - Map over the prefixes of the input with a variable d.
  Sd       - Sorts the current prefix.
 @         - Gets the element...
    _2       - At index - 2 (the second highest).
           - Print implicitly.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ḣJṢ€Ṗ€Ṫ€
```
[Try it online!](https://tio.run/##y0rNyan8///hjsVeD3cuetS05uHOaWByFZD8//9/tKGOgqmOgpGOgjGYYQkmLWIB "Jelly – Try It Online")
The first value will be 0, always, and the following numbers will be the second maximums of each prefix.
## Explanation
```
ḣJṢ€Ṗ€Ṫ€  Input: array A
 J        Enumerate indices, [1, 2, ..., len(A)]
ḣ         Head, get that many values from the start for each, forms the prefixes
  Ṣ€      Sort each
    Ṗ€    Pop each, removes the maximum
      Ṫ€  Tail each
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~87~~ 86 bytes
```
a->{int x,y=x=1<<-1;for(int c:a){if((c>x?x=c:c)>y){x=y;y=c;}System.out.print(x+" ");}}
```
[Try it online!](https://tio.run/##ZY9Nb4MwDIbv@RVWT0GDaHSbtJWPHXbeqceqhyyFKgwSlBgEQvx2Fihbt86K4sTvY@t1wVse6DpTxelzklWtDULhaqxBWbK8UQKlVuxNK9tUmYkIqZuPUgoQJbcW3rlUMBACLlbBIkeXWi1PUDmZ7tFIdT4cgZuz9RwNa2BmkYY@PPmw9eFhebws97MX/aPChbqA7jzeItsFufchuKSZX5mRrA6NbDlmfywuvVIhY8wZNL/9fS8dO/lwTCGHZOJBOrgvdH6fdEkYx0EY5drME0DsuDfInFKRdq9dInbCS3tv6JI@6hMRjfveYlYx3SBzThTS7m4DGy8ax@m6S864EFmNdDZzLd/2lor@LDeS6Qs "Java (OpenJDK 8) – Try It Online")
[Answer]
# J, 13 bytes
```
_2&{@/:~ ::#\
```
[Try it online!](https://tio.run/##y/r/P81WL95IrdpB36pOwcpKOYaLKzU5I18hTcFQwVTBSMEYSFoCscX//wA) The first element is always 1.
# Explanation
```
_2&{@/:~ ::#\
            \  Apply to prefixes
_2&{@/:~        Sort and take second-to-last atom
     /:~         Sort upwards
_2 {             Take second-to-last atom
         ::     If there's an error (i.e only one atom)
           #     Return the length of the list (1)
```
[The space matters.](http://code.jsoftware.com/wiki/Vocabulary/coco)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Ṣ-ịƊƤ
```
[Try it online!](https://tio.run/##y0rNyan8///hzkW6D3d3H@s6tuT/4fZHTWu8gTjy//9oLs5oQx0FUx0FIx0FYzDDEkxaxOpApAzBUhBZIDIBixuBxQ10FHQhFEgRUCIWAA "Jelly – Try It Online")
Outputs the first value of the input as the first value in the output. This can be removed for adding [one byte](https://tio.run/##y0rNyan8///hzkW6D3d3H@s6tuThjq7/h9sfNa3xBuLI//@juTijDXUUTHUUjHQUjMEMSzBpEasDkTIES0FkgcgELG4EFjfQUdCFUCBFQIlYAA).
## How it works
```
Ṣ-ịƊƤ - Main link. Takes l on the left
    Ƥ - Generate the prefixes of l
   Ɗ  - Run the following code over each prefix:
Ṣ     -   Sort the prefix
 -ị   -   Take the -1th index.
      -     Jelly lists are 1 indexed and modular. This means that the 0th index of a list is the final element and -1 the second to last element
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~58~~ 46 bytes
```
x=>2 to x.size map(x take _ sortBy(-_)apply 1)
```
[Try it online!](https://tio.run/##bcyxCsIwAATQvV9xYwJRbKugQgt1E/QLREqsKURjGpogqeK3x2TW4W65x9mOKx6Gy010DkcuNYR3Ql8tGmPwzp5cod/iIK077bU7o6rR6AlV8FVdwA3wcytfAg9uiIfjd4EWdhjdbiKzlnJj1IScBjNK7ZQmPUlfJGcrVrAy9iZmTSnNfkQeRTIlW/7Zi7gv2CxVhAl8whc "Scala – Try It Online")
Takes a List as an argument, and returns a Vector.
-12 bytes from user.
[Answer]
# [Zsh](https://www.zsh.org/), 32 bytes
```
for x;a+=($x)&&<<<${${(On)a}[2]}
```
[Try it online!](https://tio.run/##qyrO@J@moanxPy2/SKHCOlHbVkOlQlNNzcbGRqVapVrDP08zsTbaKLb2vyYXV5qCoYKpgpGCMZC0BGILsIghUAQkZqxgAuQbAfkGCrogAijxHwA "Zsh – Try It Online")
Reverse `O`rder `n`umerically, `<<<` print the `[2]`nd element.
[Answer]
# [Desmos](https://www.desmos.com), 44 bytes
```
f(x)=[x[1...i].sort[i-1]fori=[2...x.length]]
```
[Try it on Desmos!](https://www.desmos.com/calculator/08zdna8fty)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƒıṠṫt
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5MiVDNCVCMSVFMSVCOSVBMCVFMSVCOSVBQnQmZm9vdGVyPSZpbnB1dD0xJTJDJTIwNSUyQyUyMDIlMkMlMjAzJTJDJTIwNSUyQyUyMDklMkMlMjA1JTJDJTIwOCZmbGFncz1l)
Uses `[]` as the (arbitrary) first value.
#### Explanation
```
ƒıṠṫt  # Implicit input
ƒ      # Prefixes of the input
 ı     # Map over this list:
  Ṡ    #  Sort this list
   ṫt  #  Second-last item
       # Implicit output
```
[Answer]
# [C# (Mono)](http://www.mono-project.com/), 81 bytes
```
using System.Linq;a=>a.Select((_,i)=>a.Take(++i).OrderBy(n=>n).Skip(i-2).First())
```
[Try it online!](https://tio.run/##nY/fS8MwEMff@1ccPiUsDa4qKLV9cDhRFAcVfBCRmN3kWJtokipj9G@vaYvg8@C4X9x97nvap401tm89mQ@odj5gkyf/K3lP5itPEl0r72GV7BMfVCAN35bW8KDIMB6by9boSzLh5VX8LS5sXaMOZI2XN2jQkZa316Zt0Kn3GofpsoQNFNCrolSywmGcsTdBfKif1BbZbEZcPro1uqsdM0VpuKy29MkozbhckvOBcd5HfYt4xtYonx0FjJqR@eDiG/LORolHAqJtmMEfGFXCfi7gTEAm4GRMLkZ/3nHO84Ng8xE28aKdHkjKRtKxgHQKA3ZCdUnX/wI "C# (Mono) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
a₀ᶠb{okt}ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/FRU8PDbQuSqvOzS2ofbp3w/3@0oY6pjpGOMZC0BGKL2P9RAA "Brachylog – Try It Online")
[Answer]
## Batch, 123 bytes
```
@set/af=s=%1
@for %%n in (%*)do @call:c %%n
@exit/b
:c
@if %1 gtr %s% set s=%1
@if %1 gtr %f% set/as=f,f=%1
@echo %s%
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 15 bytes
```
(2⊃⍒⊃¨⊂)¨1↓,\∘⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR2wQNo0ddzY96JwHJQysedTVpHlph@Khtsk7Mo44Zj7oWARUpGCkYKhgoHFoPIg0VjAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
Found another 5-byter, *very* different from [Erik's solution](https://codegolf.stackexchange.com/a/138521/59487). The arbitrary value is the first element of the list.
```
ηε{Áθ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3PZzW6sPN57b8f9/tKGOqY6RjjGQtARii1gA "05AB1E – Try It Online")
---
# Explanation
```
ηε{Áθ  - Full program that reads implicitly from STDIN and outputs to STDOUT.
η      - Push the Prefixes of the list.
 ε     - Apply to each element (each prefix):
  {      - Sort the prefix list.
   Á     - Shift the list to the right by 1, such that the first element goes to the 
           beginning  and the second largest one becomes the last.
    θ    - Get the last element (i.e. the second largest)
         - Print implicitly.
```
---
Let's take an example, to make it easier to understand.
* First we get the implicit input, let's say it's `[1, 5, 2, 3, 5, 9, 5, 8]`.
* Then, we push its prefixes using `η` - `[[1], [1, 5], [1, 5, 2], [1, 5, 2, 3], [1, 5, 2, 3, 5], [1, 5, 2, 3, 5, 9], [1, 5, 2, 3, 5, 9, 5], [1, 5, 2, 3, 5, 9, 5, 8]]`.
* Now, the code maps through the list and sorts each prefix using `{` - `[[1], [1, 5], [1, 2, 5], [1, 2, 3, 5], [1, 2, 3, 5, 5], [1, 2, 3, 5, 5, 9], [1, 2, 3, 5, 5, 5, 9], [1, 2, 3, 5, 5, 5, 8, 9]]`.
* We then take the very last element and move it to the beginning: `[[1], [5, 1], [5, 1, 2], [5, 1, 2, 3], [5, 1, 2, 3, 5], [9, 1, 2, 3, 5, 5], [9, 1, 2, 3, 5, 5, 5], [9, 1, 2, 3, 5, 5, 5, 8]]`.
* Of course, now the code gets the last element of each sublist using `θ` - `[1, 1, 2, 3, 5, 5, 5, 8]` (the first one being the arbitrary value.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 16 bytes
```
{_,,:)\f{<$-2=}}
```
[Try it online!](https://tio.run/##S85KzP2fU/e/Ol5Hx0ozJq3aRkXXyLa29n9dakqs9f9oQwVTBSMFYyBpCcQWsQA "CJam – Try It Online")
Returns first element for first.
-2 thanks to [Challenger5](https://codegolf.stackexchange.com/users/61384/challenger5).
[Answer]
# [R](https://www.r-project.org/), 54 49 bytes
Thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) -5 bytes. I did not know this feature of `seq()`.
```
for(i in seq(x<-scan()))cat(sort(x[1:i],T)[2],"")
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPoTi1UKPCRrc4OTFPQ1NTMzmxRKM4v6hEoyLa0CozVidEM9ooVkdJSfO/IZcplxGXMZC0BGKL/wA "R – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~12~~ 10 bytes
The output array consists of the first element in the input array followed by the desired sequence.
```
£¯YÄ n< g1
```
[Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=o69ZxCBuPCBnMQ==&input=WzEsNSwyLDMsNSw5LDUsOF0=)
---
## Explanation
Implicit input of array `U`.
```
£
```
Map over `U`, where `Y` is the current index.
```
¯YÄ
```
Slice `U` from `0` to `Y+1`.
```
n<
```
Sort descending.
```
g1
```
Get the second element.
Implicitly output the resulting array.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~19~~ 10 bytes
*Thanks to Luis Mendo for shaving off 9 bytes!*
```
"GX@:)SP2)
```
Try it [here](https://matl.suever.net/?code=tn2w2%24%3A%22t%40%3A%29SP2%29w%5Dx&inputs=%5B1%205%202%203%205%209%205%208%5D&version=20.2.2).
### Explanation
```
"GX@:)SP2)
"                  for all the values in the input
 G                 get input
  X@:)             get values up to the iteration
      SP           sort it in descending order
        2)         get the second value
                   implicit end of loop and output
```
[Answer]
# [k](https://en.wikipedia.org/wiki/K_(programming_language)), 13 bytes
```
{x(>x)1}'1_,\
```
[Try it online!](https://tio.run/##y9bNz/7/P82qukLDrkLTsFbdMF4n5n@aup6VuoGVkn5Kapl@cUlKZp7Sf0MFUwUjBWMgaQnEFlyGCoZAPkjEWMGEywjIM1DQBRFAYQA "K (oK) – Try It Online")
```
           ,\ /sublists of increasing lengths (scan concat)
         1_   /remove the first sublist
{      }'     /for each sublist:
  (>x)        /    indices to permute sublist into largest to smallest
      1       /    get second index
 x            /    get sublist[that index]
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), ~~10~~ 8 bytes
*-2 bytes thanks to ETHproductions.*
```
∙p»îS2~ª
```
[Try it online!](https://tio.run/##y8/I/f//UcfMgkO7D68LNqo7tOr//2hDHQVTHQUjHQVjMMMSTFrEAgA "Ohm – Try It Online")
~~Uh, this is odd but I don't know how else to push a negative number...~~ I don't *really* know Ohm. :P
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras`, 41 bytes
```
[ head-clump rest [ 1 kth-largest ] map ]
```
[Try it online!](https://tio.run/##PY9NCsIwEEb3PcXnAVq0Vah6AHHjRlyVLkKMbehfTKaglJ49Tqh0hvkgb95i8hKSBusf9@vtckJlh9HovkrUh6xwcOo9ql4qh05QnTgSpB1p6WCsIvoaq3vCOZoicE3Y4YAUGeeRJ8eMDRguKHS@ioEGnmHPGhZxhX8tZbJFHCKs5lVbOo1mX6BW4hnLduwMrHKEgjcN1XErbBXeJR9vUPqQ/APZJP4H "Factor – Try It Online")
* `head-clump rest` Prefixes without the first
* `[ 1 kth-largest ] map` Map each to the second-largest element
[Answer]
# [Arturo](https://arturo-lang.io), ~~45~~ 44 bytes
```
$->a->map..2size a=>[last chop sort take a&]
```
[Try it](http://arturo-lang.io/playground?YDp6y0)
```
$->a->                  ; a function taking an argument a
    map..2size a => [   ; map over the indices of a sans the first few
        last            ; the last element
        chop            ; of a block without its last element
        sort            ; sorted
        take a &        ; prefix of input given current index
    ]                   ; end map
```
[Answer]
# Mathematica, 45 bytes
```
Sort[s[[;;i]]][[-2]]~Table~{i,2,Length[s=#]}&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/OL@oJLo4OtraOjM2NjY6WtcoNrYuJDEpJ7WuOlPHSMcnNS@9JCO62FY5tlbtf0BRZl6JgkNadLWhjoKpjoKRjoIxmGEJJi1qY/8DAA "Mathics – Try It Online")
[Answer]
# [Swift 3](https://www.swift.org), 67 bytes
```
func g(l:[Int]){print((1..<l.count).map{l[0...$0].sorted()[$0-1]})}
```
**[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598db322de80147f1a9d2322)**
# [Swift 3](https://www.swift.org), 65 bytes
```
{l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]
```
**[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598db37ede80147f1a9d2323)**
---
### How to run these?
The first one is a complete function that takes the input as a function parameter and prints the result. You can use them exactly as shown in the testing link. I decided to add instructions though, because the second type of function is used very rarely and most people don't even know of its existence. **Usage:**
```
g(l: [1, 1, 2, 2, 3, 3, 4] )
```
The second one is an anonymous function, like lambdas. You can use it exactly as you'd do it Python, declaring a variable `f` and calling it:
```
var f = {l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]
print(f([1, 1, 2, 2, 3, 3, 4]))
```
**or** wrap it between brackets and call it directly (`(...)(ArrayGoesHere)`):
```
print(({l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int])([1, 1, 2, 2, 3, 3, 4]))
```
]