text:
Make a Spiky Box
Given two positive integers, W and H, output an ASCII-art box whose border is made of slashes (/ and \) with W "spikes" on the top and bottom edges, and H "spikes" on the left and right edges. The box's interior is filled with spaces.
A "spike" is simply two slashes coming together to form an arrow shape:
/\    \/

/      \
\      /

So the output for W = 4, H = 3 would be
/\/\/\/\
\      /
/      \
\      /
/      \
\/\/\/\/

as there are 4 spikes on the top pointing up, 4 on the bottom pointing down, 3 on the left pointing left, and 3 on the right pointing right.
Here are some other input/output pairs:
W H
[spiky slash box]

1 1
/\
\/

1 2
/\
\/
/\
\/

2 1
/\/\
\/\/

2 2
/\/\
\  /
/  \
\/\/

1 3
/\
\/
/\
\/
/\
\/

3 1
/\/\/\
\/\/\/

2 3
/\/\
\  /
/  \
\  /
/  \
\/\/

3 2
/\/\/\
\    /
/    \
\/\/\/

10 1
/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\/\/\/\/\/\/

10 2
/\/\/\/\/\/\/\/\/\/\
\                  /
/                  \
\/\/\/\/\/\/\/\/\/\/

4 5
/\/\/\/\
\      /
/      \
\      /
/      \
\      /
/      \
\      /
/      \
\/\/\/\/

No lines in the output should have leading or trailing spaces. There may optionally be one trailing newline.
The shortest code in bytes wins.

Can someone who javascripts make a stack snippet for this?

Charcoal, 9 bytes
Ｂ×²Ｎ×²Ｎ/\

Try it online!
Explanation
Ｂ           Box
  ×²Ｎ       Next input as number * 2
      ×²Ｎ   Next input as number * 2
          /\ With border "/\"

Of course Charcoal has a built-in for 'draw box'

@benzene It was somewhat fortunate that he recently added the ability to draw an arbitrary string around the box, but even before then there were answers such as https://codegolf.stackexchange.com/a/120065

@Neil wait recently? When? (Do I know Charcoal less well thank you do? Haha)

@ASCII-only My bad! I got confused because of the change that regressed the cursor positioning. (The change that introduced the arbitrary border string was ca904b0 which was almost a year ago.)

@benzene Without the box builtin it's still only 13 bytes: Ｆ²«↷Ｐ…\/Ｎ»‖Ｍ¬ (takes input in height, width order).

MATL, 18 bytes
'\/',iE:]!+)O6Lt&(

Try it at MATL Online!
Explanation
Consider inputs W = 4, H = 3. The code builds the row vectors [1 2 3 4 5 6 7 8] (range from 1 to 2*W) and [1 2 3 4 5 6] (range from 1 to 2*H). Transposing the latter and adding to the former with broadcast gives the matrix
2  3  4  5  6  7  8  9
3  4  5  6  7  8  9 10
4  5  6  7  8  9 10 11
5  6  7  8  9 10 11 12
6  7  8  9 10 11 12 13
7  8  9 10 11 12 13 14

Modular indexing into the string \/ produces the desired result in the matrix border:
/\/\/\/\
\/\/\/\/
/\/\/\/\
\/\/\/\/
/\/\/\/\
\/\/\/\/

To remove the non-border values, we set them to 0 (when interpreted as char it is displayed as space):
/\/\/\/\
\      /
/      \
\      /
/      \
\/\/\/\/

Commented code:
'\/'    % Push this string. Will be indexed into
,       % Do twice
  i     %   Input a number
  E     %   Multiply by 2
  :     %   Range
]       % End
!       % Transpose
+       % Add
)       % Index
O       % Push 0
6L      % Push [2 -1+1j]. As an index, this means 2:end
t       % Duplicate
&(      % Write 0 into the center rectangle. Implicit display

Python 2, 69 68 bytes
-1 thanks to Kevin Cruijssen
lambda w,h:'/\\'*w+'\n'+'\\%s/\n/%s\\\n'%(('  '*~-w,)*2)*~-h+'\\/'*w

Try it online!

\\%s can become \%s and \\/ can become \/.

Haskell, 90 88 87 82 bytes
1 6 bytes saved thanks to Lynn
a#b=[1..a]>>b
x!y|i<-(x-1)#"  "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"]

Try it online!
Still feels really long,  I'll see what I can do.

Defining a#b=[a..b] and replacing all occurences saves one byte: a#b=[a..b];x!y|i<-2#x>>"  "=(1#x>>"/\\"):(2#y>>['\\':i++"/",'/':i++"\\"])++[1#x>>"\\/"]

Oh, a#b=[1..a]>>b;x!y|i<-(x-1)#"  "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"] actually saves 6~

@Lynn Thanks!  You've really been catching my slack lately.

@Lynn I got it to work but at the cost of another byte.

05AB1E, 14 bytes
„/\|∍`S¦`).B∞∊

Try it online!
Explanation
„/\|∍`S¦`).B∞∊   Arguments: x, y
„/\              Push the string "/\"
   |             Push inputs as array: [x,y]
    ∍            Push the string extended/shortened to those lengths
     `           Flatten
      S          Push seperate chars of second string
       ¦`        Remove first char and flatten again
         )       Wrap stack to an array
          .B     Squarify
            ∞∊   Mirror on both axes

This only creates the top left corner, x characters wide and y characters tall. It then mirrors this on both axes:
x=3, y=2

/\/|
\  |
---+

JavaScript (ES6), 84 bytes
Takes input in currying syntax (w)(h).
w=>h=>'/\\'[R='repeat'](w)+`
${`\\${p='  '[R](w-1)}/
/${p}\\
`[R](h-1)}`+'\\/'[R](w)

Demo

let f =

w=>h=>'/\\'[R='repeat'](w)+`
${`\\${p='  '[R](w-1)}/
/${p}\\
`[R](h-1)}`+'\\/'[R](w)

function upd() { O.innerHTML = W.value+'x'+H.value+'\n\n'+f(W.value)(H.value) }
upd()
<input id=W type=range value=5 min=1 max=10 oninput="upd()">
<input id=H type=range value=5 min=1 max=10 oninput="upd()">
<pre id=O>

Swift 3, 166 bytes
func f(a:Int,b:Int){let k=String.init(repeating:count:),n="\n";var r="\\"+k("  ",a-1)+"/";print(k("/\\",a)+n+k(r+n+String(r.characters.reversed())+n,b-1)+k("\\/",a))}

Full test suite.
The closure version is a bit longer, unfortunately (175 bytes):
var g:(Int,Int)->String={let k=String.init(repeating:count:),n="\n";var r="\\"+k("  ",$0-1)+"/";return k("/\\",$0)+n+k(r+n+String(r.characters.reversed())+n,$1-1)+k("\\/",$0)}

Test suite with the closure version.

Retina, 77 73 bytes
\d+
$*
 1+|1(?=1* (1+))
$1¶
1
/\
.((..)*.)
/$1¶$1/
¶$

(?<=¶.+).(?=.+¶)

Try it online! Link includes test cases. Takes input in the format <height> <width>. Explanation:
\d+
$*

Convert the inputs to unary.
 1+|1(?=1* (1+))
$1¶

Multiply the inputs, but add a newline so that the result is a rectangle.
1
/\

Create the spiky top.
.((..)*.)
/$1¶$1/

Duplicate each spiky row, but with the spikes offset on the second row.
¶$

Delete trailing newlines.
(?<=¶.+).(?=.+¶)

Delete the inside of the box. (Note space on last line.)

C (gcc), 170 166 158 155 108 105
-3 bytes thanks to cleblanc
x,y;f(w,h){for(y=h*=2;y--;puts(""))for(x=w*2;x--;)putchar(!x|x==w*2-1|!y|y==h-1?x&y&1|~x&~y&1?47:92:32);}

Try it online!
I think this can be golfed further with a less straightforward approach, I'll see what I can do when I find the time.
Ok I cannot find any other way to reduce the number of bytes for that code.
Explanation: a simple double-loop printing the box char by char.
When printing a border: if both x and y coordinates are either even or odd, it displays a /, otherwise, a \ is displayed
If not a border, a space character is displayed instead

You can shave off another 3 bytes by moving the puts("") into the first for loop like this x,y;f(w,h){for(y=h*=2;y--;puts(""))for(x=w*2;x--;)putchar(!x|x==w*2-1|!y|y==h-1?x&y&1|~x&~y&1?47:92:32);}

APL (Dyalog), 41 39 bytes
Prompts for a list of [H,W]
'\'@2@1⊢¯1⌽@1{⌽⍉⍵,'/\'⍴⍨≢⍵}⍣4⊢''⍴⍨2×⎕-1

Try it online!
⎕-1 prompt for input (mnemonic: stylized console) and subtract 1
2× multiply by two
''⍴⍨ use that to reshape an empty string (pads with spaces)
⊢ yield that (serves to separate it from 4)
{…}⍣4 apply the following function four times:
 ≢⍵ tally (length of) the argument
 '/\'⍴⍨ cyclically reshape "/\" to that length
 ⍵, append that to the right side of the argument
 ⌽⍉ transpose and mirror (i.e. turn 90°)
¯1⌽1 cyclically rotate the 1st row one step to the right
⊢ yield that (serves to separate it from 1)
'\'@2@1 put a backslash at the 2nd position of the 1st major item.

Excel, 95 bytes
=REPT("/\",A1)&"
"&REPT("\"&REPT(" ",2*A1-2)&"/
/"&REPT(" ",2*A1-2)&"\
",B1-1)&REPT("\/",A1)

///, 172 117 bytes
So, because the output consists of ///s and  whitespaces, there should be submissions in those 2 languages.
Put the input after the code in W,H as unary number (unary for /// is allowed, thanks to Challenger5 for suggestion) (use * to represent digit, separate with ,) format.
/W/VV//V/\\\///`/\\\\\\\\\\\\\V/,/W>+  V`/`\>+W  !V!``WV>+WV-  V`\
`\W+  V`/
`/W-!V`\
W``\\V`\V>!//!*/+%-%!//*/  //%/
Try it online! (with input W=4, H=3)

You can skip the parsing by taking input in Unary.

Also, I should mention that this is very impressive! Good job!

Python 3, 87 82 bytes
Edit: Saved 5 bytes thanks to @officialaimm, @Mr.Xcoder and @tsh
def f(a,b,n="\n"):r="\\"+"  "*~-a+"/";print("/\\"*a+n+(r+n+r[::-1]+n)*~-b+"\\/"*a)

Try it online!

81 bytes in python 2 after some improvements

If you want to keep it in Python 3, *(b-1) can be *~-b, for -2 bytes.

@officialaimm Why " "*2*~-a? Just "__"*~-a.

@tsh Yes, you are right... Haha didn't realize that...

@officialaimm will keep it Python 3, did however save some bytes due to you, Mr.Xcoder and tsh

SOGL V0.12, 22 21 13 bytes
/\”m;HΙ»mč+╬¡

Try it Here! (expects both inputs on stack so .. (and " because a string hasn't been explicitly started) - take number input twice is added for ease-of-use)
Explanation:
/\”            push "/\"
   m           mold to the 1st inputs length
    ;          get the other input ontop of stack
     H         decrease it
      Ι        push the last string - "/\"
       »       rotate it right - convert to "\/"
        m      mold "\/" to the length of 2nd input - 1
         č     chop into characters
          +    prepend the 1st molded string to the character array of the 2nd
           ╬¡  quad-palindromize

:D it isn't beating Charcoal here

@ASCII-only because charcoal has a built-in for this :p (and SOGLs really made for complicated & long challenges anyway)

J, 48 bytes
' '&((<,~<<0 _1)})@(+:@[$(1&|.,:])@('\/'$~+:)@])

ungolfed
' '&((< ,~ <<0 _1)}) @ (+:@[ $ (1&|. ,: ])@('\/' $~ +:)@])

explanation
                       (+:@[ $ (1&|. ,: ])@('\/' $~ +:)@])    creates box, but interior filled with slashes
                                           ('\/' $~ +:)@]       take right arg, W, doubles it, then fills that
                                          @                       many characters with '\/' repeating
                               (1&|. ,: ])                      stacks (,:) the above on top of itself rotated
                                                                  by one char, producing top and bottom spikes
                              $                                 reshape to..
                       (+:@[                                    double the length of the left arg, height
                                                                  this creates the sides, as well as a filled interior
                     @
' '&((< ,~ <<0 _1)})                                          removes slashes from interior by using the complement
                                                                form of amend }.  ie, replace everything but the first
                                                                and last row and first and last col with a space

Try it online!

33 bytes ' '(<,~<<0 _1)}'\/'{~=/&(2|i.)&+:. Amend is great here.

ooooh, very nice improvement

30 bytes '/\ '{~2(<,~<<0 _1)}2|+/&i.&+: with some refactoring

05AB1E, 19 bytes
4FNÈi¹}·„\/NÉiR}N·Λ

Try it online!
Takes arguments reversed.

Hmm, I smell... Canvas Mode?

Haskell, 84 79 bytes
w%h=[[last$"/\\"!!mod(x+y)2:[' '|x>1,y>1,x<2*w,y<2*h]|x<-[1..2*w]]|y<-[1..2*h]]

Try it online! Example usage: 3%6 yields a list of lines. Use mapM putStrLn $ 3%6 to pretty-print the box.

I got my answer down below yours with the help of Lynn, but I'd love to see you beat it again.

@WheatWizard There you go ;)

Java 8, 141 bytes
A curried lambda from width to height to output.
w->h->{String f="/",b="\\",t=f,o=b,p="";char i=1;for(;i++<w;t+=b+f,o+=f+b)p+="  ";t+=b;o+=f;for(i=10;--h>0;)t+=i+b+p+f+i+f+p+b;return t+i+o;}

Try It Online (no, return t+i+o; was not intentional)
Ungolfed lambda
w ->
    h -> {
        String
            f = "/",
            b = "\\",
            t = f,
            o = b,
            p = ""
        ;
        char i = 1;
        for (; i++ < w; t += b + f, o += f + b)
            p += "  ";
        t += b;
        o += f;
        for (i = 10; --h > 0; )
            t += i + b + p + f + i + f + p + b;
        return t + i + o;
    }

This solution is atypically picky about input size since a char is used to count up to the width input. Fortunately, the algorithm is bad enough that at those sizes program completion is probably already an issue. I chose to use char for the loop index so I could reuse it later as a cheap alias for '\n'.

Mathematica, 87 bytes
Table[Which[1<i<2#2&&1<j<2#," ",OddQ[i+j],"\\",1>0,"/"],{i,2#2},{j,2#}]~Riffle~"
"<>""&

Try it in Mathics (it prints extra spaces at the start of most lines for some reason), or at the Wolfram sandbox! Takes two integers as input.
It's a fairly naïve solution, but all of the clever things I tried had more bytes. Something that nearly works is
ArrayPad[Array[" "&,2#-2],1,{{"/",s="\\"},{s,"/"}}]~Riffle~"\n"<>""&

except it fails if either dimension is 1 (input is a list containing the dimensions).

Pyth, 40 39  38 bytes
+++*Q"/\\"b*tE+++K++\\*d*2tQ\/b_Kb*"\/

This takes the two integers separated by a newline.
Full test suite.

R, 160 bytes 152 bytes
p=function(x,n){paste(rep(x,n),collapse='')}
function(w,h){f=p(' ',w*2-2)
cat(paste0(p('/\\',w),'\n',p(paste0('\\',f,'/\n/',f,'\\\n'),h-1),p('\\/',w)))}

Try it online!
Thanks BLT for shaving off 8 bytes.

Do you ever use the s function?

The s function is what you call to make the spikey box

Got it. You can get down to 152 bytes if you remove whitespace and the s= bit. Anonymous functions are allowed.

Good to know anon functions are allowed

Ruby, 62 61 60 bytes
->r,c{["/\\"*c]+["\\#{w="  "*~-c}/",?/+w+?\\]*~-r+["\\/"*c]}

-1 byte thanks to Arnauld
Try it online!

Actually, 38 bytes
"/\"*;.R;l¬' *"\/"@j;R(D(╗WD(;.(;.(Wé╜

Try it online!

J, 39 bytes
(' \/'{~=/&(2&|)(*>:)~0=*/&(*|.))&i.&+:

Try it online!
Takes two arguments as height on the LHS and width on the RHS.

Nice work, as usual.  Interesting approach, too.

@Jonah No, your idea is much better using amend. If combined with half of mine...

><>, 180 Bytes
0&0\
a*+>i68*-:0(?v$
/)\^0&1v?)0&~/
? 0 v:$<
/ \:<-1oo'/\'
\~$:@2*0&\
'/'1>&o1->a\ /'/'>o$:2*>1-:1)?\~$&1=?\
'\'0//?(3:o/?/'\'/     \o*48  /      \
/?)0\ &:&1=/;
\  \:~
'/'/\<oo'\'

VBA (Excel) , 161 Bytes
Sub a()
c=[A2]*2
r=[B2]*2
For i=1To r
For j=1To c
b=IIf(i=1 Or j=1 Or i=r Or j=c,IIf((i+j) Mod 2,"\","/")," ")
d=d & b
Next
d=d & vbCr
Next
Debug.Print d
End Sub

Golfed Sub (139 Bytes): Sub b
c=[2*A1]
r=[2*B1]
For i=1To r
For j=1To c
Debug.?IIf(i=1Or j=1Or i=r Or j=c,IIf((i + j)Mod 2,"\","/")," ");
Next
Debug.?
Next
End Sub

Anonymous immediate window function version of above (113 Bytes): c=[2*A1]:r=[2*B1]:For i=1To r:For j=1To c:?IIf(i=1Or j=1Or i=r Or j=c,IIf((i + j)Mod 2,"\","/")," ");:Next:?:Next

Perl 5, 83 + 1 (-n) = 84 bytes
say"/\\"x($q=$F[0]);print(("\\".($s=$"x(2*$q-2))."/$//$s\\$/")x--$F[1]);say"\\/"x$q

Try it online!

dc, 123 bytes
?1-sesf[/\]su[lfsh[lunlh1-dsh0<q]dsqx]dsrx[[
\]P[lf2*2-st[32Plt1-dst0<z]dszx]dsmx[/
/]Plmx92Ple1-dse0<l]slle0<l10P[\/]sulrx

It's far from the shortest, but, if one takes the last two lines and rotates them pi/2 radians clockwise to an "upright" position, it kind of looks like a totem pole.
Takes input as two space-separated integers.
Try it online!

Currently the longest answer here. I thought that was Java's job...

Don't worry, there's now a Java solution, and it's longer.

Mathematica, 116 bytes
(c=Column;o=Table;v=""<>o[" ",2*#-2];w=""<>o["/\\",#];c[{w,c@o[c[{"\\"<>v<>"/","/"<>v<>"\\"}],#2-1],Rotate[w,Pi]}])&

Rotate[w,Pi] is equivalent to w~Rotate~Pi, as is o["/\\",#] to "/\\"~o~#

I know infix notation and I always use it when I really need 1 byte.In this case I just let it go... ;-)

I did not doubt your knowledge of infix notation; I just wanted to reduce the byte count. You know, in the spirit of golfing and such.

V, 18 bytes
Ài/\Ùæ$Àäkllòjjkè

Answer wouldn't require the ll if <M-h>ollow left 2 char columns alone :(
Try it online!

C# (.NET Core), 188 bytes
a=>b=>string.Join("\n",new int[2*b].Select((x,i)=>string.Concat(string.Concat(new int[a].Select(y=>i%2==0?"/\\":"\\/")).Select((y,j)=>i>0&i<2*b-1&j>0&j<2*a-1?" ":""+y))))

Byte count also includes:
using System.Linq;

Try it online!
I started making explanation command-by-command but it stopped making sense midway... Basic gist is to make full spiky box, and then hollow out the middle. I used Linq for the sake of using Linq, probably can be shorter using just standard iterations.
Here's explanation going middle-out (the inner-most command first):
First, create rows for the full box, and concatenate to a single string
string.Concat(new int[a].Select(y => i % 2 == 0 ? "/\\" : "\\/"))

Then get each character in a row, and if it isn't the outline of the box, replace with space, concatenate them back into one string for each row
string.Concat(PREVIOUS_STEP.Select((y, j) => i > 0 & i < 2 * b - 1 & j > 0 & j < 2 * a - 1 ? " " : "" + y))

Finally, get each row and concatenate them together with newlines (also includes generating of a collection for rows)
string.Join("\n", new int[2 * b].Select((x, i) => PREVIOUS_STEP));

Jelly, 19 bytes
JṖḊ
Ḥ+þ/ị⁾\/⁶Ç¦€Ç¦Y

Try it online!
How?
JṖḊ - Link 1, middle indexes: list
J   - range of length [1,2,3,...,length-1,length]
 Ṗ  - pop             [1,2,3,...,length-1]
  Ḋ - dequeue           [2,3,...,length-1]

Ḥ+þ/ị⁾\/⁶Ç¦€Ç¦Y - Main link: list of numbers [w,h]
Ḥ               - double (vectorises) -> [2*w,2*h]
   /            - reduce by:
  þ             -   outer product with:
 +              -     addition ->  [[1,2,...,w],[2,3,...,1+w],...,[h+1,h+2,...,h+w]]
     ⁾\/        - literal ['\','/']
    ị           - index into (vectorises) -> ["/\/\.../\","\/\/...\/",...,"\/\/...\/"]
             ¦  - sparse application:
            Ç   - ...to indexes: call the last link as a monad (the middle ones)
          ¦€    - ...of: sparse application for €ach:
         Ç      -        ...to indexes: call the last link as a monad (the middle ones)
        ⁶       -        ...of: a space character (blank out the middle entries)
              Y - join with newlines
                - as a full program: implicit print

APL (Dyalog), 30 bytes
' \/'[(⌽⌈⊖)3|((-0=⌊)*+)/↑⍳2×⎕]

Try it online!

Excel VBA, 89 Bytes
Anonymous VBE immediate window function that takes input as w from [A1] and h from [B1] and then outputs to the VBE immediate window.
a=[Rept("/\",A1)]:?a:s=space(2*[A1-1]):For i=1To[B1-1]:?"\"s"/":?"/"s"\":Next:?Mid(a,2)"/


text:
Bubble the brackets!
There are a few questions on this site about balancing brackets, and checking whether brackets are balanced. I propose it's now time to use those balanced brackets for something!
In mathematics and programming, brackets are like bubbles, isolating everything inside form everything outside so that whatever's inside can do its thing in peace and whatever's outside only sees one object. However, a string of brackets is one-dimensional, while bubbles usually are at least two dimensional. That means that bubbles are free to move around one another as long as they never touch each other or cross between the inside and the outside of any other bubbles.
Challenge
The input is a string of matched brackets of a single type, either round (), square [], curly {} or angle <>. It's up to you what kind you want your program to accept, and a program that only accepts a single kind of brackets is accepted. (Imaginary bonus if your program can handle any of them, massive imaginary bonus points if it can handle all of them in the same input.) The input cannot contain anything between the brackets, although trailing whitespaces are allowed.
The output is all possible reorganisations (in arbitrary order, and including the original input) of those brackets that yields the same configuration of bubbles, with no two identical strings. That means that with an input of ()(), the output is also just ()(), even though it's technically two bubbles that could swap places. For the massive imaginary bonus, an input of {}[]() will of course lead to an output of 6 different elements / strings / lines.
Two configurations of bubbles are "the same" if you can make one into the other by moving bubbles around, without letting any bubble cross from inside another bubble to outside it, or from outside to inside. If you liken nested parentheses to trees (each matched pair is one node, and every matched pair within is a subnode, and each matched pair within there is a subnode of those again, and so on) where the subnodes of any given node are ordered, then a single configuration of bubbles is a tree where the nodes are unordered.
Any reasonable output format will do, like returning a list of strings or a list of list of single characters or a single string with some kind of whitespace, or printing to stdoutor stderr with some form of visible whitespace character (most commonly newline or space) between each reorganisation.
Trailing spaces for each reorganisation and trailing and preceeding newlines / empty list elements before and after the actual output is allowed. You should use the same kind of brackets in your output as you accept in your input. Apart from the brackets, newlines and spaces as specified here, and whatever separator you use, nothing should be printed (including invisible / zero-width characters).
The score is the number of bytes in the code; lowest count for each language wins. You may note whether you get an imaginary bonus, either regular or massive, but it doesn't affect your score. Actual bonuses are too hard to balance right.
Input-output examples
Example 1:
Input:
()(())

Output:
()(())
(())()

Example 2:
Input:
(()())()()

Output:
(()())()()
()(()())()
()()(()())

Example 3:
Input:
(()(()))()

Output:
((())())()
()((())())
(()(()))()
()(()(()))

Why can't we get ((())) in example 1? or ()()()?  It seems like you are missing permutations for each input.

@WheatWizard That wouldn't give the same configuration of bubbles: one large bubble with two empty bubbles inside.

@WheatWizard as far as I understand, you can't take a bubble from inside another bubble to the outside, or vice versa.

@WheatWizard I added a small explanation.

Are angled brackets <> allowed?

@StepHen You know what, let's allow angle brackets. I just didn't think about those.

Btw, Welcome to PPCG! Nice first challenge!

Can I take input as a nested array e.g. [[[],[[]]],[]] for example 3?

@Neil Only explicit representations of the matched brackets in the form of a string, or an array (null-terminated if you want) of chars, or something similar is allowed as input.

@Mr.Xcoder Thanks. I don't think I have many challenges in me; I'm not creative in that way. But the ideas I do get I try to make as much of as possible. I basically joined just to post this one puzzle, although I do like to read other puzzles and answers.

@Arthur, do you mean it would have to be a 1-dimensional array of characters?

@Dopapp Yes, I do. No structural hints in the input format.

As @Mr.Xcoder wrote: nice challenge. And tough!

Haskell, 227 210 208 205 bytes
import Data.List
l=last
a!x=init a++[l a++[x]]
h[]=[""]
h(x:y)=["("++z++")"++t|z<-v x,t<-h y]
g(a,r)x|x=='('=(a+1,l$(r++h[]):[r!x|a>0])|1>0=(a-1,l$r:[r!x|a>1])
v s=nub$h=<<(permutations.snd$foldl g(0,[])s)

Try it online!
This one was tough!
Golfed a little bit
Saved two bytes thanks to Laikoni
Save two bytes thanks to Bruce Forte
I'm not sure this works in every case. Some explanations:

a!x add the String x to the last list of String in a (a is of type [[String]])
snd$foldl(\(a,r)x->if x=='('then(a+1,last$(r++[[]]):[r!x|a>0])else(a-1,last$r:[r!x|a>1]) uses the shorter conditional to express the simple idea: split a String on root )(s. E.g. "(()(()))()" gives ["()(())", ""].
We need to process each part of the split, then to gather and join all the strings to get the correct output:

h processs a list of parts: it applies v to the first part and combines the result to the process of the remaining parts.
v aggregates the results for each permutation of the parts, and remove the duplicates.

To add a broader view: you have basically a tree (not a binary one) with empty nodes. Leave are (). You have to produce all the permutations of the branches for each node, but you may not take a branch from a node and put it on another node. I did a kind of depth first search.

You can drop the parentheses around init a.

CJam, 18 bytes
{~{_{{B}%e!}&}:B~}

Try it online!
-2 thanks to Business Cat.
Receives input as a string containing only []. Returns a list of permutations (empty lists are the same as empty strings in CJam, so instead of [] you'll be getting "").

Why is the output for [][] just ""? - Should the input be enclosed in an extra set of []? If so why is there an extra set of [] around what (maybe?) is the output for the aforementioned example? Also the question states "You should use the same kind of brackets in your output as you accept in your input. Apart from the brackets, newlines and spaces as specified here, and whatever separator you use, nothing should be printed", so I'm not sure a mix of [] and "" is acceptable.

@JonathanAllan Yes I think you need to enclose [][] in an extra pair of []. For the others I'm not really sure they're invalid.

I think you can do _{{B}%e!}& instead of _!!{{B}%e!}*

@BusinessCat Does & short-circuit or something?

& runs the block only if the other value is truthy

JavaScript (Firefox 30-57), 222 bytes
s=>(g=a=>a+a?[for(x of g(a[0]))for(y of a.keys())for(z of g(a.slice(1)))(z.splice(y,0,x),z)]:[a])(eval(`[${s.replace(/]\[/g,`],[`)}]`)).map(g=a=>`[`+a.map(g).join``+`]`).sort().filter(s=>t<(t=s),t=``).map(s=>s.slice(1,-1))

Takes [] strings. Explanation:
s=>(                                Inner function to permute an array
 g=a=>a+a?[                         If array is not empty
  for(x of g(a[0]))                 Permute the first element of the array
  for(y of a.keys())                Generate a list of insertion points
  for(z of g(a.slice(1)))           Permute the rest of the array
  (z.splice(y,0,x),z)]:             Make all possible permutations
  [a]                               Otherwise return a list of an empty array
)(eval(`[${                         Convert the string to a nested array
   s.replace(/]\[/g,`],[`)}]`)      ... inserting commas where necessary
).map(                              Process the results
 g=a=>`[`+a.map(g).join``+`]`       Recursively convert back to string
).sort().filter(s=>t<(t=s),t=``     Check for duplicates
).map(s=>s.slice(1,-1))             Remove outer `[]`s

Python 2, 353 350 331 Bytes
s=input()
f=lambda i,t=0:i+1if t<0else f(i+1,t-1)if"("<s[i+1]else f(i+1,t+1)
c=[(x,f(x))for x in range(len(s))if")">s[x]]
p=lambda l:[[]]if len(l)<1else[x for y in p(l[1:])for x in[y[:i]+[l[0]]+y[i:]for i in range(len(y)+1)]]
print[''.join(x)for x in p([s[c[x][0]:c[x][1]]for x in range(len(c))if all(c[x][1]>y[1]for y in c[:x])])]

Receives string of () as input and prints the result.
Try it here!
I avoided using itertools.permutations with help from Paolo's answer to this question.
Thank you to Business Cat for finding 3 bytes, and thank you to Mr. Xcoder for an incredible 19 bytes!
Explanation

Create a list of tuples of the indices of each () pair in the input string.
Drop any tuples from the list that are surrounded by another () pair.
Slice the string at the indices of the remaining tuples.
Make a list of each permutation of the list of slices.
Join the list with a new line for printing.

I see a few bytes that could be shaved. You have some whitespace that can be removed, namely after print and at spots like i+1 if (could be i+1if). Also at one spot you have y[0:i], you can omit the 0.

Thank you, @BusinessCat! My IDE complains on a few of those, so I'm still learning some of the code golf tricks.

342 bytes (-8 bytes) by reordering some conditionals in order to remove whitespace.

340 bytes (-10 bytes) by using lexicographical comparison over equality checking.

331 bytes (-19 bytes) because the challenge allows returning a list of Strings. yay, we beat Mathematica :-)

Wow, nice additions @Mr.Xcoder. Can't believe it's this short now.

@Mr.Xcoder I also count unnecessary spaces in my Mathematica solution, and use 3-bytes identifier name.

Mathematica, 337 bytes
Not to get code-golf points, but to show the usage of Permutations and Distribute in this problem. There may be better approaches, though.
(seq : sequence, alt : alternatives)
SetAttributes[alt, {Flat, OneIdentity}]
StringTake[
  StringReplace[ToString[
    ToExpression["{" <> StringReplace[#, "}{" -> "},{"] <> "}"]
        /. List -> Permutations@*seq
       /. List -> alt
      /. seq -> (Distribute[seq@##, alt] &)
     /. {seq -> List, alt -> Alternatives}],
   {", " -> "", "} | {" -> "\n"}],
  {2, -2}] &

Take input as a string, using curly brackets { and }. Output a multi-line string.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Smallest unseen, but no sharing digits!
Challenge
Here at PPCG, we sure do like our sequences, so here's a fun another one.
Let's define a(n) as being the smallest non-negative integer X that is not equal to any a(k) (0 < k < n), and a(n-1) and X do not share any decimal digits. a(0) = 0
Given an input n > 0, output such a(n).
For example, for input n = 13, we have a(13) = 20, since a(12) = 11 and 20 is the smallest non-negative integer we haven't seen yet that doesn't share any decimal digits with 11.
Sequence
Here are the first 20 terms to get you started. This is sequence A067581 on OEIS.
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 11, 20, 13, 24, 15, 23, 14, 25

Rules

The input and output can be assumed to fit in your language's native integer type.
The input and output can be given in any convenient format.
You can choose to either 0-index, as I am here in my examples, or 1-index for your submission. Please state which you're doing.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Can we get n > 1 (or n ≥ 2) as input? (1-indexing)

@EriktheOutgolfer Sure, that's fine. I apparently missed that bullet point when copy-pasting, because that's a standard of my challenges.

The scatter plot sure looks nice:)

Python 2, 85 bytes
-1 byte thanks to Dead Possum

n=0,
exec"i=0\nwhile set(`i`)&set(`n[-1]`)or i in n:i+=1\nn+=i,;"*input()
print n[-1]

Try it online!

n=0, for -1 byte?

@DeadPossum yeah, thanks c:

Japt, 18 bytes
@A{!ZøA «As oX}a}g

Test it online! I've just added the g feature used here, but it's something I've been meaning to add for a long time (and this pushed me over the edge, because my non-g solution was around 35 bytes).
Explanation
@   A{!ZøA «  As oX}a}g
XYZ{A{!ZøA &&!As oX}a}gU
                           Implicit: U = input integer
   {                 }gU   Starting with [0, 1], return the U'th item generated by
XYZ{                 }     this function: (X = previous item, Y = index, Z = full array)
    A{             }a        Return the smallest non-negative integer A where
      !ZøA &&                  Z does not contain A (A is not yet in the sequence), and
             !As oX            A.toString() does not contain any of the same chars as X.
                           Implicit: output result of last expression

This makes my head hurt! But, then I've barely glanced at any of the function methods in Japt.

Isn't the default rule that you can't add something to the language after the question is given? It would be trivial otherwise to just always create a new built-in that solves the challenge, making them all arbitrarily short.

@trlkly I believe it's allowed within good judgement. The built-in I added is much more general-purpose than just for this one answer. I think someone could theoretically add a built-in that solves the challenge entirely, but an answer like that would be sure to be received very poorly.

Pyth, 20 bytes
eu+Gf!|/GT@`eG`T0Q]0

Try it online! or Try the test suite.

Mind if I add a test suite to your answer?

@Mr.Xcoder go ahead.

Haskell, 79 bytes
f 0=0
f x=[i|i<-[1..],all((/=i).f)[1..x-1],all(`notElem`show(f$x-1))$show i]!!0

The code is horribly inefficient. To calculate bigger values, i.e. > 12, add f x|x<11=x between the two lines (implemented a g in the TIO link).
Try it online!

Haskell, 78 bytes
n!k|r:_<-[j|j<-[1..],all(/=j)k,all(`notElem`show n)$show j]=n:r!(r:k)
(0![]!!)

It would be even more efficient if the second argument to ! would not be the list of seen numbers but of unseen numbers. But I can't do that without using more bytes.
Try it online!

Husk, 18 bytes
!¡₁;0
ḟȯ¬V€d→⁰d-⁰N

A 1-indexed solution.
Try it online!
Edit: fixed bug for +1 byte.
Explanation
Husk's built-in iteration function ¡ has many meanings.
Here, I'm using "construct infinite list by repeatedly appending new elements computed from the existing ones".
The second line is the helper function that computes a new element:
ḟȯ¬V€d→⁰d-⁰N  Takes a list of existing elements, e.g. x = [0,1,...,10]
           N  The positive integers
         -⁰   with elements of x removed:        [11,12,13,...
ḟȯ            Find an element n of this list that satisfies:
        d     Digits of n.
   V          Is any of them
    €         an element of
     d        the digits of
      →⁰      the last element of x?
  ¬           Negate.
              Returns 22.

The first line is the main function:
!¡₁;0  Takes an integer k.
 ¡     Iterate adding new elements to the list
   ;0  [0]
  ₁    using the helper function,
!      take k'th element of result.

I've added Husk to the golfing language list; please let me know if I got any details wrong.

JavaScript (ES6), 82 bytes
0-indexed.
f=(n,x=[1,p=0])=>n--?f(x[(g=k=>x[k]||(k+'').match(`[${p}]`)?g(k+1):p=k)(0)]=n,x):p

Demo

f=(n,x=[1,p=0])=>n--?f(x[(g=k=>x[k]||(k+'').match(`[${p}]`)?g(k+1):p=k)(0)]=n,x):p

for(n = 0; n < 50; n++) {
  console.log('a(' + n + ') = ' + f(n))
}

Mathematica 115 Bytes
Still room to golf this down - and maybe use recursion (thus speeding it up).
(For[z={0};i=1,Length@z<#,
For[i=1,!FreeQ[z,i]||!DisjointQ@@IntegerDigits/@{l,i},i++];
z~AppendTo~i;l=Last@z;
];l)&

Original verbose code, with the same basic idea:
MakeSequenceA067581[n_]:=Module[{list={0}, innerCounter=1},

While[Length@list<n,
innerCounter=1;
(* inner loop *)While[Or[MemberQ[list,innerCounter],Intersection[IntegerDigits[Last@list],IntegerDigits[innerCounter]]!={}],innerCounter++];
AppendTo[list,innerCounter];
];
list
]

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Многочлены Чебышёва (Chebyshev Polynomials)
Chebyshev Polynomials are a family of orthogonal polynomials that pop up in all kinds of places in math, and they have a lot of quite interesting properties. One characterization of them is that they are the unique polynomials that satisfy \$T_n(\cos(x)) = \cos(nx)\$.
Challenge
Given an nonnegative integer \$n\$, you should output the \$n\$-th Chebyshev Polynomial. \$T_n(x)\$.
Definition
The \$n\$-th Chebyshev Polynomial is given by following three term recursion:
$$\begin{align}
T_0(x) & = 1 \\
T_1(x) & = x \\
T_{n+1}(x) & = 2xT_n(x) - T_{n-1}(x)
\end{align}$$

Details
If your language has a native polynomial type, you can use that one as an output, otherwise you should output a list of coefficients in ascending- or descending order, or as a string representing a polynomial.
This is code-golf so the shortest code in bytes wins
Examples
T0(x) = 1
T1(x) = x
T2(x) = 2x^2 - 1
T3(x) = 4x^3 - 3 x
T4(x) = 8x^4 - 8x^2 + 1
T5(x) = 16x^5 - 20x^3 + 5x
T10(x) = 512x^10 - 1280x^8 + 1120x^6 - 400x^4 + 50x^2 - 1

In the descending degree list format we'd get T3(x) = [4,0,-3,0] and in the ascending degree format we'd get T3(x) = [0,-3,0,4]

If I output a list, can I output 0 1 (i.e. 0*x+1) for T_0?

As long the order of the monomials is consistent that is ok!

@flawr is 2*x*(2*x**2 - 1) - x ok as output for 3 for polynom supportive lang, or do we need the representation as desc coeffs?

Ah I unfortunately did not specify that further, so I guess that is ok, as it represents a polynomial.

Are floating-point inaccuracies acceptable? i.e. T_5(n) = [0, 5, 3.55271e-15, -20, 0, 16]

@miles Yes that should be ok!

Is outputting a list of coefficients, but skipping the ones that are zero because the polynomial is odd/even okay?

No I think that this should not be allowed, as that way you cannot determine the actual polynomial by the output alone without any additional information.

@Lynn thanks, added!

Mathematica, 15 bytes
#~ChebyshevT~x&

Of course, Mathematica has a builtin.
If an alternative input form is allowed (10 bytes):
ChebyshevT

takes an integer n and a variable.

Couldn't have guessed, huh. :P

Octave, 39 bytes
@(n)round(2^n/2*poly(cos((.5:n)/n*pi)))

Try it online!
Explanation
cos((.5:n)/n*pi) builds a vector with the roots of the polynomial, given by

poly gives the monic polynomial with those roots. Multiplying by 2^n/2 scales the coefficients as required. round makes sure that results are integer in spite of numerical precision.

Clever as always :)

Pari/GP, 12 bytes
Yes, a builtin. Shorter than Mathematica.
polchebyshev

Try it online!

Without builtin:
Pari/GP, 34 bytes
f(n)=if(n<2,x^n,2*x*f(n-1)-f(n-2))

Try it online!

Does polchebyshev take only one input and return the polynomial?

@JungHwanMin Yes. x is the default indeterminate.

Haskell, 62 bytes
t n|n<2=1:[0|n>0]|x<-(*2)<$>t(n-1)++[0]=zipWith(-)x$0:0:t(n-2)

Try it online!
flawr saved a byte.

This is very elegant! (I keep forgetting about zipWith for vector operations.)

I think you can even save one more byte by using guards: t n|n<2=1:[0|n>0]|x<-(*2)<$>t(n-1)++[0]=zipWith(-)x$0:t(n-2), that way you can remove the middle pair of parenthesis in the last line :)

I think you have to change 0: to 0:0: - OP just disallowed this kind of skipping the zeroes.

CJam (21 bytes)
1a2,qi{0X$+2f*@.-}*;`

This is a full program: the equivalent as an anonymous block is the same length:
{1a2,@{0X$+2f*@.-}*;}

Online demo

MATL, 17 bytes
lFTi:"0yhEbFFh-]x

Coefficients are output in increasing order of degree.
Try it online! Or verify all test cases.
Explanation
For input n, the code applies the recursive relation n times. The two most recent polynomials are always kept on the stack. When a new polynomial is computed, the oldest is removed.
At the end, the second-last polynomial is displayed (the last polynomial is deleted), as we have done one too many iterations.
l        % Push 1
FT       % Push [0 1]. These are the first two polynomials
i:"      % Input n. Do the following n times
  0      %   Push 0
  y      %   Duplicate most recent polynomial
  h      %   Concatenate: prepends 0 to that polynomial
  E      %   Multiply coefficients by 2
  b      %   Bubble up. This moves second-most recent polynomial to top
  FF     %   Push [0 0]
  h      %   Concatenate: appends [0 0] to that polynomial
  -      %   Subtract coefficients
]        % End
x        % Delete. Implicitly display

Python + SymPy, 66 bytes
from sympy.abc import*
T=lambda n:n<2and x**n or 2*x*T(n-1)-T(n-2)

Try it online!
With descending coefficients representation
from sympy import*
x=symbols('x')
T=lambda n:n<2and x**n or expand(2*x*T(n-1)-T(n-2))

Try it online!

[1,x][n] -> x**n

Jelly, 18 bytes
Cr1µ’ßḤ0;_’’$ß$µỊ?

Try it online!
Returns a list of coefficients in ascending order.
There is another solution for 17 bytes with floating-point inaccuracies.
RḤ’÷Ḥ-*ḞÆṛæ«’µ1Ṡ?

Try it online!
Explanation
Cr1µ’ßḤ0;_’’$ß$µỊ?  Input: integer n
                Ị   Insignificant - abs(n) <= 1
                    If true, n = 0 or n = 1
   µ                  Monadic chain
C                       Complement, 1-x
 r1                     Range to 1
                    Else
               µ      Monadic chain
    ’                   Decrement
     ß                  Call itself recursively
      Ḥ                 Double
       0;               Prepend 0
         _              Subtract with
            $             Monadic chain
          ’’                Decrement twice
              $           Monadic chain
             ß              Call itself recursively

14 bytes

SageMath, 25 bytes
lambda n:chebyshev_T(n,x)

Try it online

J, 33 bytes
(0>.<:)2&*1:p.@;9:o._1^+:%~1+2*i.

Try it online!
Assumes that floating-point inaccuracies are acceptable and creates the emoji (0>.<:)
For 41 bytes, there is another solution that avoids floats.
(0&,1:)`(-&2((-,&0 0)~2*0&,)&$:<:)@.(>&1)

Try it online!

Ruby + polynomial, 59 58+13 = 72 71 bytes
Uses the -rpolynomial flag.
f=->n{x=Polynomial.new 0,1;n<2?[1,x][n]:2*x*f[n-1]-f[n-2]}

Python 2, 79 bytes
f=lambda n:n>1and[2*a-b for a,b in zip([0]+f(n-1),f(n-2)+[0,0])]or range(1-n,2)

Try it online!

Axiom, 40 bytes
f(n,x)==(n<2=>x^n;2*x*f(n-1,x)-f(n-2,x))

results
(9) -> for i in [0,1,2,3,4,5,10] repeat output ["f(y)",i,"=", f(i,y)]
   ["f(y)",0,"=",1]
   ["f(y)",1,"=",y]
                   2
   ["f(y)",2,"=",2y  - 1]
                   3
   ["f(y)",3,"=",4y  - 3y]
                   4     2
   ["f(y)",4,"=",8y  - 8y  + 1]
                    5      3
   ["f(y)",5,"=",16y  - 20y  + 5y]
                      10        8        6       4      2
   ["f(y)",10,"=",512y   - 1280y  + 1120y  - 400y  + 50y  - 1]
                                                               Type: Void

it is possible define one substitution law for formula in Axiom use above f() function
for expansion of cos(n*x) where n is one integer
(9) -> o:=rule cos(n*%y)==f(n,cos(%y))
   (9)  cos(%y n) == 'f(n,cos(%y))
                    Type: RewriteRule(Integer,Integer,Expression Integer)
                                                              Time: 0 sec
(10) -> b:=o cos(20*x)
   (10)
                 20                18                16                14
     524288cos(x)   - 2621440cos(x)   + 5570560cos(x)   - 6553600cos(x)
   +
                  12                10               8              6
     4659200cos(x)   - 2050048cos(x)   + 549120cos(x)  - 84480cos(x)
   +
               4            2
     6600cos(x)  - 200cos(x)  + 1
                                                 Type: Expression Integer
                       Time: 0.48 (EV) + 0.02 (OT) + 0.10 (GC) = 0.60 sec

C# (.NET Core), 126 bytes
f=n=>n==0?new[]{1}:n==1?new[]{0,1}:new[]{0}.Concat(f(n-1)).Select((a,i)=>2*a-(i<n-1?f(n-2)[i]:0)).ToArray();

Byte count also includes:
using System.Linq;

Try it online!
The function returns polynomial as an array of coefficients in ascending order (from x^0 to x^n)
Explanation:
f = n =>                          // Create a function taking one parameter (int)
    n == 0 ? new[] { 1 } :        // If it's 0, return collection [1]
    n == 1 ? new[] { 0, 1 } :     // If it's 1, return collection [0,1] (so x + 0)
    new[] { 0 }                   // Else create new collection, starting with 0
        .Concat(f(n - 1))         // Concatenate with f(n-1), effectively multiplying polynomial by x
        .Select((a, i) => 2 * a - (i < n - 1 ? f(n - 2)[i] : 0))
                                  // Multiply everything by 2 and if possible, subtract f(n-2)
        .ToArray();               // Change collection to array so we have a nice short [] operator
                                  // Actually omitting this and using .ElementAt(i) is the same length, but this is my personal preference

JavaScript (ES6), 65 bytes
f=n=>n?n>1?[0,...f(n-1)].map((e,i)=>e+e-(f(n-2)[i]||0)):[0,1]:[1]

Inefficient for large n. Interesting but sadly also inefficient:
n=>[...Array(n+1)].map(g=(m=n,i)=>i<0|i>m?0:m<2?i^m^1:g(m-1,i-1)*2-g(m-2,i))

Very efficient for 68 bytes:
f=(n,a=[1],b=[0,1])=>n?f(n-1,b,[0,...b].map((e,i)=>e+e-(a[i]||0))):a

Returns an array of coefficients in ascending order.

Stax, 19 bytes
╛5%Ö←Äⁿ¿æ╔Dë!é╔J╗yì

Run and debug it
zipping takes a lot of bytes.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Return of the Hydra Slayer
Its been a while since you killed that hydra, you basked in the glory for years, but now people are calling you washed up, a has been.  Well its time you prove them wrong, you've heard the whereabouts of annother hydra.  Simply kill it and you will be awarded all the glory you deserve.
You arrive at the armory to receive your swords but they're all out of regular swords all they have left are Sectors.  An n-sector will divide the number of heads on a Hydra by n, but can only be used if the number of heads is divisible by n.
Once again you are going to write some code to help you slay the hydra.
Your code will take as input the number of head the hydra, begins the fight with, the number of heads the hydra grows each turn, and a list of n-sectors you can use.  Your code will output an optimal pattern of moves to slay the hydra as quickly as possible
Each turn of the fight you may select a single sword to use, if after a slice the hydra has only one head you win, if not it grows heads.  You may never make no move, and if there are no possible moves available you lose.
If no solution is possible you may output anything other than a solution, e.g. an empty list, nothing, the number zero, etc.
This is code-golf so answers will be scored as their byte counts, with less being better.
Test cases
Here are some super basic test-cases, more test-cases will be added upon request.
24 heads, 1  heads per turn, [2,3] -> [3,3,2,3]
25 heads, 2  heads per turn, [2,3] -> No solutions
4  heads, 2  heads per turn, [2]   -> No solutions
4  heads, 3  heads per turn, [2,5] -> [2,5]
10 heads, 17 heads per turn, [2, 3, 7, 19] -> No solutions
10 heads, 6  heads per turn, [1,16] -> [1,16]
6  heads, 2  heads per turn, [2, 3, 5] -> [2, 5]
125 heads, 1  head per turn, [1, 2, 3, 127] -> [1, 1, 127]

Can the hydra only have 1 head to start?

@ETHproductions You do not have to handle that case.

Can we assume that the list is sorted?

@ETHproductions Yes you may.  I don't see why not.

A 1-sector is basically a "skip turn" sword?

@Neil Yes, it can always be used and doesn't reduce the hydra's heads.  It is still useful because there is no way to skip turns otherwise.

@FunkyComputerMan I see we can assume the list is sorted. Does that mean I could assume it is sorted largest to smallest?

@FunkyComputerMan Also, can we assume that if the 1-sector is an available option, there will be at least one other sector available? Otherwise, I would need to add a special case for that condition because it will never be winnable.

JavaScript, 191 190 bytes
Saved a byte thanks to Step Hen
(h,t,s)=>eval(`r=[],d=0,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>(a=h/w)==1?d=w:!(a%1)&!r[a+=t]?r[q.push([...p,w],a),a]=1:0);d?(q=[],p).push(d):0}d?p:[]`)

f=(h,t,s)=>eval(`r=[],d=0,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>(a=h/w)==1?d=w:!(a%1)&!r[a+=t]?r[q.push([...p,w],a),a]=1:0);d?(q=[],p).push(d):0}d?p:[]`)

console.log(`[${f(24, 1, [2,3])}]`);
console.log(`[${f(25, 2, [2,3])}]`);
console.log(`[${f(4, 2, [2])}]`);
console.log(`[${f(4, 3, [2,5])}]`);
console.log(`[${f(10, 17, [2, 3, 7, 19])}]`);
console.log(`[${f(10, 6, [1,16])}]`);
console.log(`[${f(125, 1, [1, 16])}]`);
console.log(`[${f(1024, 3, [1, 2, 137])}]`);

Python 2, 169 195 222 bytes
+26 bytes to properly handle cyclic head regeneration on bad weapon picks. (Thanks to @ThePirateBay for pointing it out)
+27 bytes to fix certain edge cases causing errors.
lambda n,p,w:g(n,n,p,w[::-1])[:-1]
def g(n,b,p,w,a=[]):
 if b<2:return[1]
 for x in w:
	if n%x<1and n/x+p!=n and n not in a:
	 try:
		l=[x]+g(n/x+p,n/x,p,w,[n]+a)
	 	if l and l[-1]!=0:return l
	 except:return[0]
 return[0]

Try it online!

Usually the resuable bit means you can't create global vars, modify them, and assume they are back to the original value next time. Dunno what the policy is on erroring here - full programs would definitely be allowed to error out for empty output.

210 bytes

Possible 208 bytes.

VB.NET (.NET 4.5), 439 + 35 (imports) = 474 bytes
Requires Imports System.Collections.Generic
Const N=Nothing
Function Z(h,r,a,Optional c=N,Optional p=N,Optional ByRef s=N)
If c Is N Then
c=New List(Of Long)
p=New List(Of Long)
End If
If s IsNot N And s?.Count<c.Count Then Return N
If p.Contains(h)Then Return N
p.Add(h)
For i=0To a.Count-1
Dim w=a(i)
If h Mod w=0Then
c.Add(w)
If h\w=1And(s Is N Or s?.Count>c.Count)Then
s=New List(Of Long)
s.AddRange(c)
End If
Z(h\w+r,r,a,c,p,s)
c.RemoveAt(c.Count-1)
End If
Next
Z=s
End Function

The function Z takes two Int64 (number of heads and head regrow rate), and a List(Of Int64) (Sectors), and returns a List(Of Int64) (the ordered choice of Sectors). ReturnsNothing` if there is no solution.
Assumes the Sectors are presented in sorted order from largest to smallest.
The Optional parameters are for the recursive calls to save state. They track the current order of Sectors in use, the shortest order of Sectors ever, and the number of heads ever encountered. If we encounter the same number of heads again, there has to have been a shorter way to reach it.
The only ordering of Sectors that matters is I need 1 to be last if it exists. Otherwise, the hydra will might grow without bounds because I could at every turn just use the 1 Sector and never try any other.
I declared a constant N to represent Nothing, shaving off 6 bytes each time I wanted to use Nothing.
And/Or are not short-circuiting, so I use the null conditional operator (?.) to avoid object null errors. In real code, I would use AndAlso/OrElse which do short-circuit.
Try it online!

Z un-golfed for readability
Public Function Z(currentHeads As Long, regrowRate As Integer, weapons As ISet(Of Long), Optional currentWeapons As List(Of Long) = Nothing, Optional previousHeads As List(Of Long) = Nothing, Optional shortestWeapons As List(Of Long) = Nothing) As List(Of Long)

    ' initial call
    If currentWeapons Is Nothing Then
        currentWeapons = New List(Of Long)
        previousHeads = New List(Of Long)
    End If

    ' we've made more moves than our best so far
    If shortestWeapons IsNot Nothing AndAlso shortestWeapons.Count <= currentWeapons.Count Then
        Return Nothing
    End If

    ' exit, we've been here before
    If previousHeads.Contains(currentHeads) Then
        Return Nothing
    End If

    ' keep track of previous state to prevent duplicate paths
    previousHeads.Add(currentHeads)

    For Each w In weapons

        ' save 1 for last
        If w = 1 Then Continue For

        If currentHeads Mod w = 0 Then
            currentWeapons.Add(w)

            If currentHeads \ w = 1 Then
                If shortestWeapons Is Nothing OrElse shortestWeapons.Count > currentWeapons.Count Then
                    shortestWeapons = New List(Of Long)(currentWeapons)
                End If
            End If

            Dim answer = A(currentHeads \ w + regrowRate, regrowRate, weapons, currentWeapons, previousHeads, shortestWeapons)
            If answer IsNot Nothing Then
                If shortestWeapons Is Nothing OrElse shortestWeapons.Count > answer.Count Then
                    shortestWeapons = New List(Of Long)(answer)
                End If
            End If

            currentWeapons.RemoveAt(currentWeapons.Count - 1)
        End If
    Next

    If weapons.Contains(1) Then
        currentWeapons.Add(1)

        Dim answer = A(currentHeads \ 1 + regrowRate, regrowRate, weapons, currentWeapons, previousHeads, shortestWeapons)
        If answer IsNot Nothing Then
            If shortestWeapons Is Nothing OrElse shortestWeapons.Count > answer.Count Then
                shortestWeapons = New List(Of Long)(answer)
            End If
        End If

        currentWeapons.RemoveAt(currentWeapons.Count - 1)
    End If

    Return shortestWeapons
End Function


text:
Words crossing over
Input:
Two strings (NOTE: the order of input is important).
Output:
Both words/sentences start on lines with one empty line in between them. They 'walk' horizontally 'next to each other'. But when they have the same character at the same position, they cross each other, and then continue walking 'next to each other'.
Confusing you say? Let's give an example:
Input: Words crossing over & Ducks quacking:
Word  quack n
    s      i g
Duck  cross n  over

Excuse the bad MS paint..
Challenge rules:

We always first go back walking a straight line after we've 'crossed over' before we can cross over again (see test case above {1} - where ing is equal, but after we've crossed on i, we first have to go back walking straight (thus ignoring n), before we can cross again on g).
The inputs can be of different length, in which case the longer one continues walking in a straight line (see test cases 1, 2, 4 & 6).
Both inputs can be the same (see test case 3).
The inputs won't contain any tabs nor new-lines.
Spaces are ignored as characters that are the same (as an edge case), in which case the next (non-space) character after that - if any - is crossing over instead (see test cases 3, 5 & 6).
The inputs can have no adjacent (non-space) characters on the same position at all, in which case both just walk in a straight line horizontally (see test cases 2).
Even if the first character is equal, we always start two lines apart (see test cases 3 & 6).
Trailing spaces and a single trailing new-line are optional.
You can assume the inputs will only contain printable ASCII characters (new-lines and tabs excluded).
The inputs are case-sensitive, so A and a aren't equal, and won't cross over (see test case 7).
Both the inputs lengths will always be at least 2.
Input & output can be in any reasonable format. Can be a single String with new-lines; a String-array/list; printed to STDOUT; 2D array of characters; etc.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:
1. Input: "Words crossing over" & "Ducks quacking"

1. Output:
Word  quack n
    s      i g
Duck  cross n  over

2. Input: "bananas" & "ananas"

2. Output:
bananas

ananas

3. Input: "I see my twin!" & "I see my twin!"

3. Output:
I  e   y  w n
  s e m  t i !
I  e   y  w n

4. Input: "Is the weather nice?" & "Not really, no.."

4. Output:
Is th ally, no..
     e
Not r  weather nice?

5. Input: "Codegolf & Programming Puzzles" & "The golfer might solve puzzles"

5. Output:
Code o f & Programming P z l s
    g l                 u z e
The  o fer might solve p z l s

6. Input: "Can you turn the lights off?" & "Can you try to solve this?"

6. Output:
C n  o   urn the  ve  s off?
 a  y u t        l   t
C n  o   ry to so igh his?

7. Input: "one Ampere" & "two apples"

7. Output:
one Am les
      p
two ap ere

8. Input: "Words crossing" & "Words Quacking"

8. Output:
W r s cross n
 o d       i g
W r s Quack n

Japt, 56 47 33 bytes
y ®m+S éBv ©Zê¬©Zx ?°B:B=c2)¯3Ã·y

Test it online! Takes input as an array of two strings.
I am a total moron... y ® is a million times easier to use on two different-length strings than U¬íV¬@...
Explanation
y ®   m+S éBv © Zê¬ © Zx ?° B:B= c2)¯  3Ã ·  y
y mZ{Zm+S éBv &&Zêq &&Zx ?++B:B=Bc2)s0,3} qR y

              Implicit: U = array of two strings
y             Transpose U, padding the shorter string with spaces in the process.
mZ{        }  Map each pair of chars Z by this function: (we'll call the chars X and Y)
  Zm+S          Append a space to each char, giving X + " " + Y + " ".
  Bv            If B is divisible by 2
  &&Zêq           and Z is a palindrome (X and Y are the same)
  &&Zx ?          and Z.trim() is not empty (X and Y are not spaces):
    ++B           Increment B. B is now odd; the top and bottom strings are swapping.
  :             Otherwise:
    B=Bc2         Ceiling B to a multiple of 2. (0 -> 0, 1 -> 2, 2 -> 2, etc.)
  é       )     Rotate the string generated earlier this many chars to the right.
  s0,3          Take only the first 3 chars of the result.
qR            Join the resulting array of strings with newlines.
y             Transpose rows with columns.
              Implicit: output result of last expression

B is a variable that keeps track of which state we're in:

B % 4 == 0 means first word on top, but ready to switch;
B % 4 == 1 means we've just switched;
B % 4 == 2 means second word on top, but ready to switch;
B % 4 == 3 means we've just switched back.

B happens to be preset to 11; since 11 % 4 == 3, the first column always has the first word on top. We increment B any time the words swap positions, or any time it's odd (with B=c2).

APL (Dyalog), 64 bytes
{C←⎕UCS⋄1↓e⊖' '⍪1 0 1⍀⍵⊖⍨≠\e←C(2/⊃l)⎕R(l←C⌽⍳2)C(0@0=⌿⍵)∧' '≠1⌷⍵}

Try it online!

If the strings start with 3 identical letters, this intersects the third letters, not the second ones. I am unsure if this is the correct result, I have asked the OP.

@Mr.Xcoder Thanks. Should be fixed now.

Ok, nice solution then. If you have time, maybe you can add an explanation :P

@Mr.Xcoder Yes, I always do. (Ping me if you see any unexplained answer of mine!)

That's why I am always delighted to see your answers :) - Because I understand your submissions more than I understand mine.

@Mr.Xcoder Thank you. I appreciate your words.

@Adám Yeah surely...or maybe? Might have something to do with this as well...oh and an unexplained answer! Or maybe two...? And something I don't quite get.

@EriktheOutgolfer Thanks. Done.

@EriktheOutgolfer All done. Thanks.

Charcoal, 69 bytes
ＡＥ⮌θιθＡＥ⮌ηιηＷ∧θη«Ａ⊟θεＡ⊟ηδＡ∧¬∨φ⁼ε ⁼εδφ¿φ«εＡθδＡηθＡδη»«↑↓ε↓↗δ»»¿θ↑↓↑⮌⁺θη

Try it online! Link is to verbose version of code. Explanation:
ＡＥ⮌θιθＡＥ⮌ηιη        Turn the input strings into arrays and reverse them
Ｗ∧θη«               While both valus still have characters left
     Ａ⊟θεＡ⊟ηδ       Extract the next pair of characters
     Ａ∧¬∨φ⁼ε ⁼εδφ   Determine whether this is a crossing point
     ¿φ«εＡθδＡηθＡδη  If so then print the character and switch the value
      »«↑↓ε↓↗δ»»     Otherwise print the two characters apart
¿θ↑↓                Move to print any remaining characters accordingly
↑⮌⁺θη               Print any remaining characters

Python 2, 217 210 bytes
-1 byte thanks to officialaimm
a,b=map(list,input())
n=max(len(a),len(b))
c=[' ']*n
a=(a+c)[:n]
b=(b+c)[:n]
for i in range(1,n):
 if a[i]==b[i]!=' '==c[i-1]:c[i]=a[i];a[i]=b[i]=' ';a[i:],b[i:]=b[i:],a[i:]
print'\n'.join(map(''.join,[a,c,b]))

Try it online!

1 byte by predefining s=' '

@officialaimm I did some changes, now it have the same byte count =/

Haskell, 142 138 bytes
g(a:b)f(c:d)|f>0,a==c,a>' '=[' ',a,' ']:g d 0b|1<2=[a,' ',c]:g b 1d
g[]_[]=[]
g b f d=g(max" "b)f$max" "d
a&b=[[j!!i|j<-g a 0b]|i<-[0..2]]

Try it online!
How it works:
g                    -- function g constructs a list of lists of three characters
                     --   the 1st char belongs to the upper line,
                     --   the 2nd char to the middle line and
                     --   the 3rd char to the lower line
      f              -- flag f indicates if crossing is allowed or not
 (a:b) (c:d)         -- strings to cross
  |f>0               -- if crossing is allowed
      ,a==c          -- and both strings start with the same char
           ,a>' '    --   that is not a space
   =[' ',a,' ']      -- return space for upper/lower line and char a for the middle line
      :g d 0b        -- and go on with crossing disabled and strings swapped
 |1<2=               -- else
   [a,' ',c]         -- keep chars in their lines and
      :g b 1d        --  go on with crossing enabled

g[]_[]=[]            -- base case: stop when both strings are empty

g b f d=             -- if exactly one string runs out of characters
 g(max" "b)f$max" "d --   replace it with a single space and retry

a&b=                 -- main function
          i<-[0..2]  -- for each line i from [0,1,2]
       j<-g a 0b     -- walk through the result of a call to g with crossing disabled
    j!!i             -- and pick the char for the current line

+1 nice answer. It does seem to have one little bug however, because it now starts crossing when the first two characters are equal, like in tests 3, 6 and 8 (TIO). Also, I think you forgot a word in your explanation sentence "return space for upper/lower line and a ¿¿¿ for the middle line".

@KevinCruijssen: Thanks for finding the bug. Luckily it's easy to fix: just start with g 0. Regarding the missing word: "a" as in "variable named a", but that's indeed confusing, so I reworded it.

Ah, that a. :) I personally use a in my explanations when indicating to the variables, although usually it's clear enough without. Thanks for the clarification, and I was indeed expecting a pretty easy bug-fix for it.

Not sure how to do 'a' (with ' being replaced with a back-tick) in a comment anymore, which is what I wanted to say.. (So I use back-ticks around variables, inside my code-blocks.)

JavaScript (ES6), 112 bytes
(a,b,c='',g=([a,...A],[b,...B],w)=>a?w&a==b&a>' '?' '+g(B,A,c+=a):a+g(A,B,1,c+=' '):'')=>g(a,b)+`
`+c+`
`+g(b,a)

Ungolfed:
f=
(a,b,                                    //the inputs
 c='',                                   //c will hold the middle sentence
 g=([a,...A],[b,...B],w)=>               //define a function to walk through the strings
                                         //w will be false if we're at the beginning,
                                         //... or if we've just done a swap
     a?                                  //are there any letters left?
       w&a==b&a>' '?' '+g(B,A,c+=a):     //if we haven't just swapped and the letters match,
                                         //... add the current letter to c
                                         //... and recurse swapping the strings
                    a+g(A,B,1,c+=' '):   //else add a space to c and continue processing
                    ''
)=>
g(a,b)+'\n'+                             //call g with a, b
c+'\n'+                                  //output c
g(b,a)                                   //call g with b, a

Test cases:

f=
(a,b,c='',g=([a,...A],[b,...B],w)=>a?w&a==b&a>' '?' '+g(B,A,c+=a):a+g(A,B,1,c+=' '):'')=>g(a,b)+`
`+c+`
`+g(b,a)

console.log(f('Words crossing over','Ducks quacking'));
console.log('____________');
console.log(f('bananas','ananas'));
console.log('____________');
console.log(f('I see my twin!', 'I see my twin!'));
console.log('____________');
console.log(f('Is the weather nice?', 'Not really, no..'));
console.log('____________');
console.log(f('Codegolf & Programming Puzzles', 'The golfer might solve puzzles'));
console.log('____________');
console.log(f('Can you turn the lights off?', 'Can you try to solve this?'));
console.log('____________');
console.log(f('one Ampere', 'two apples'))
console.log('____________');
console.log(f('Words crossing','Words Quacking'));
console.log('____________');

Perl 5, 211 bytes
@a=map[/./g],<>;$b=1;($f,@{$r[$i]})=$a[0][$i]eq$a[1][$i]&&$f&&$a[0][$i]ne$"?(0,$",$a[0][$i],$",$t=$b++):(1,$a[$t%2][$i],$",$a[$b%2][$i]),$i++while$a[0][$i]||$a[1][$i];for$i(0..2){print$r[$_][$i]for 0..$#r;say''}

Try it online!
# Perl 5, 234 bytes
fixed the bug Kevin pointed out
@a=map[/./g],<>;$l=@{$a[0]}>@{$a[1]}?@{$a[0]}:@{$a[1]};$b=1;@{$r[$_]}=$a[0][$_]eq$a[1][$_]&&$_&&$r[$_-1][1]eq$"&&$a[0][$_]ne$"?($",$a[0][$_],$",$t=$b++):($a[$t%2][$_],$",$a[$b%2][$_])for 0..$l;for$i(0..2){print$r[$_][$i]for 0..$l;say}

Try it online!

Hi, when I try to test the test case "Can you turn the lights off?" & "Can you try to solve this?" I seem to be getting an error: Modification of non-creatable array value attempted, subscript -1 at .code.tio line 1, <> line 2. Is this a bug, or am I doing something incorrect? Here is the TIO.

Bug.  When the first two characters were the same, an array subscript was -1, which is only valid if there is data in the array.  Fixed it with 4 more bytes.

APL (Dyalog), 50 bytes
{3↑(0,+\2∨/2|{⍵⌈a×1+1,¯1↓⍵}⍣≡a←>⌿2=⌿3↑⍵)⊖⍵⍀⍨¯1*⍳4}

Try it online!
⍵⍀⍨¯1*⍳4 gives the matrix:
Words.crossing.over
...................
Ducks.quacking.....
...................

(the dots represent spaces).  Its columns will be rotated by different amounts so the first three rows end up looking like the desired result - hence the 3↑ near the beginning.  The rest of the algorithm computes the rotation amounts.
Within the parens: 3↑⍵ creates a matrix like
Words.crossing.over
Ducks.quacking.....
...................

and 2=⌿ compares its rows pairwise, i.e. first string vs second string and
second string vs the all-spaces row.
0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 1 1

We are interested in where the former is true (1) and the latter false (0), so
we reduce with >⌿ to get a boolean vector named a.
0 0 0 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0

Now, in every stretch of 1-s we need to zero out the even occurrences because
no two twists can occur next to each other. First we obtain a numbering like:
0 0 0 0 1 0 0 0 0 0 0 1 2 3 0 0 0 0 0

by, loosely speaking, replacing a[i] with a[i]*max(a[i-1]+1, a[i]) until
the result stabilises: {⍵⌈a×1+1,¯1↓⍵}⍣≡, and we take that mod 2: 2|
0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0

Now we know where the twists will occur. We copy each 1 to the left - 2∨/
(pairwise "or"):
0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0

and compute the partial sums - +\
0 0 0 0 1 2 2 2 2 2 2 3 4 5 6 6 6 6 6

That gives us the column rotation amounts we needed in the beginning. Modulo 4 is implied.

Nice! Even 14 bytes shorter than Adám. Could you add an explanation (I'm sure you are making it as we speak, but in case you aren't.. ;)

Explanations only take away the pleasure of figuring out how it works on your own... :)

05AB1E, 31 bytes
ζεËNĀ¾Èyðå_Pi¼ë¾É½}yð«S¾._¨}øJ»

Port of @ETHproductions's Japt answer, but with two minor differences:
1) I take the input as a 2D list of characters instead of list of strings.
2) The counter_variable in 05AB1E is 0 by default, instead of 11 (or 3) like the B in Japt, so the NĀ is added as additional check inside the map (and I rotate towards the right instead of left).
Try it online or verify all test cases.
Explanation:
ζ                  # Zip/transpose (swapping rows/columns) the (implicit) input-list
                   # with space filler by default to create pairs
 ε          }      # Map each pair `y` to:
  Ë                #  Check if both values in the pair are equal
  NĀ               #  Check if the map-index is not 0
  ¾È               #  Check if the counter_variable is even
  yðå_             #  Check if the pair contains no spaces " "
  Pi               #  If all checks are truthy:
    ¼              #   Increase the counter_variable by 1:
   ë               #  Else:
    ¾É             #   Check if the counter_variable is odd
      ½            #   And if it is: increase the counter_variable by 1
   }               #  Close the if-else
    yð«            #  Add a space after both characters in the pair
       S           #  Convert it to a list of characters (implicitly flattens)
        ¾._        #  Rotate this list the counter_variable amount of times towards the right
           ¨       #  And then remove the last character
             ø     # Zip/transpose; swapping rows/columns
              J    # Join each inner character-list to a single string
               »   # Join everything by newlines (and output implicitly)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Running second maximum of a list
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

My English isn't the best, how is k determined?

@LiefdeWen Output a list containing the answer for each k.

1 is not, strictly speaking, the second largest value of 1,1 (2nd example) it's the second value when sorted descending.

Maybe I'm just stupid (although I suspect I could really have the weekend started..), but I'm still not sure how this works. Could someone ELI5 the last test case to me? The first two test cases I can solve by just looping over the list, determining the current minimum of the list, and then remove that item (or easier: sort list and remove last item). It gives the correct results for the first two test cases, but is obviously wrong (and will give -1, 0, 0, 1, 1, 2 for the last test case.)

@KevinCruijssen Remember the two largest numbers you have seen. In the last case, you start with 2 being the largest, and output nothing/whatever since it doesn't make sense at this point. Then you change to 1 and 2 at the next iteration, so you output 1. This stays the same until you reach the 2 at the end, and then you have 2 and 2 as the largest and second largest

Does it make any sense at all to add an excel-based answer to this, if it relies on the input being entered one value per cell in a column and returns the output one value per cell in an adjacent column?

@Adam I guess it makes some sense. But I'm not exactly sure how to score such submissions. Maybe you could find some information on the meta.

@jimmy23013 I found two relevant threads on meta, one of which was closed as a duplicate of the other (although the answers were fairly different: https://codegolf.meta.stackexchange.com/questions/10199/what-mouse-interactions-are-allowed-by-default-as-part-of-input-output AND https://codegolf.meta.stackexchange.com/questions/10141/how-should-we-handle-excel-answers-with-drag-down-formulas )  One says yes, the other says no.  My answer isn't all that exciting anyways, so I will skip it.

@Adam There are many Excel answers on this site. It's only the scoring part that I'm not sure of. I don't think anyone had the opinion that such answers shouldn't be posted. And at least the answer could be compared with other Excel answers, like the cases of Minecraft and Piet.

This could also make an interesting restricted-complexity challenge.

@xigoi For such a simple problem, theoretically, compilers and interpreters could automatically optimize O(n^2) answers into O(n). Most implementations don't do that, and doing that could be quite challenging itself. But it's like free points (or penalty) for the golfers because of the language creator's hidden work (or lack of it) that isn't really related to how elegant the golfed code appears to be, which I suppose is not a good idea.

05AB1E, 5 bytes
ηεà\à

Try it online!
Returns [] (arbitrary value) for first.

η¦ε{¨θ should work for 6 bytes

@Adnan Of course >_< found a better way anyways though...

Interesting... Z©KZ®‚¹sÃ was what I was thinkinh, didn't know à was even a thing!

Found another 5-byte alternative. I used Áθ instead.

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!

You could map →hO instead and save a byte.

I suppose that the Husk command "ḣ" (prefixes) must have subtly changed since this was originally posted, as this answer seems to work with only 6 bytes now...

Python 2, 54 bytes
lambda x:[sorted(x[:i])[-2]for i in range(2,1+len(x))]

Try it online!

Nekomata, 4 bytes
poil

Attempt This Online!
p     Prefix
 o    Sort
  i   Init (remove the last element)
   l  Last

Accidentally, poil means hair in French.

I've been waiting so long for one of these golf langs to spell an actual word!

JavaScript (ES6), 58 51 50 bytes
Saved 1 byte thanks to @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

I think a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[]) is only 50.

@Neil Nice. :-)

Python 2, 45 bytes
f=lambda l:l[1:]and f(l[:-1])+[sorted(l)[-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.

Jelly, 8 bytes
ḣJṢ€Ṗ€Ṫ€

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

@Challenger5 I don't believe that works

@Challenger5 That doesn't work...

@EriktheOutgolfer Oh, ok.

Pyth, 8 bytes
m@Sd_2._

Try it online! or Try the Test Suite!

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.

Java (OpenJDK 8), 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!

+1 for int x,y=x=. I didn't know separate declaration and assignment could be done in the same statement.

J, 13 bytes
_2&{@/:~ ::#\

Try it online! 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.

Jelly, 5 bytes
Ṣ-ịƊƤ

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.
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

Scala, 58 46 bytes
x=>2 to x.size map(x take _ sortBy(-_)apply 1)

Try it online!
Takes a List as an argument, and returns a Vector.
-12 bytes from user.

Make that 46 bytes by sorting in reverse, actually.

Zsh, 32 bytes
for x;a+=($x)&&<<<${${(On)a}[2]}

Try it online!
Reverse Order numerically, <<< print the [2]nd element.

Desmos, 44 bytes
f(x)=[x[1...i].sort[i-1]fori=[2...x.length]]

Try it on Desmos!

Thunno 2, 5 bytes
ƒıṠṫt

Try it online!
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

Ohm, 10 8 bytes
-2 bytes thanks to ETHproductions.
∙p»îS2~ª

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

Okay, 0 2- seems very strange...

Just looking at the docs (I know nothing about Ohm), could you do 2~?

@TEHProductions Oh, much better. Thanks!

CJam, 16 bytes
{_,,:)\f{<$-2=}}

Try it online!
Returns first element for first.
-2 thanks to Challenger5.

{_,,:)\f{<$-2=}} is two bytes shorter.

C# (Mono), 81 bytes
using System.Linq;a=>a.Select((_,i)=>a.Take(++i).OrderBy(n=>n).Skip(i-2).First())

Try it online!

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

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.

Brachylog, 10 bytes
a₀ᶠb{okt}ᵐ

Try it online!

R, 54 49 bytes
Thanks to 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!

seq(x<-scan()) is shorter by a few bytes.

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%

APL (Dyalog), 15 bytes
(2⊃⍒⊃¨⊂)¨1↓,\∘⊢

Try it online!

05AB1E, 5 bytes
Found another 5-byter, very different from Erik's solution. The arbitrary value is the first element of the list.
ηε{Áθ

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.

MATL, 19 10 bytes
Thanks to Luis Mendo for shaving off 9 bytes!
"GX@:)SP2)

Try it here.
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

@LuisMendo Wow! Goes to show how much I know about MATL. Thanks for the help!

k, 13 bytes
{x(>x)1}'1_,\

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]

Factor + grouping.extras, 41 bytes
[ head-clump rest [ 1 kth-largest ] map ]

Try it online!

head-clump rest Prefixes without the first
[ 1 kth-largest ] map Map each to the second-largest element

Arturo, 45 44 bytes
$->a->map..2size a=>[last chop sort take a&]

Try it
$->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

Mathematica, 45 bytes
Sort[s[[;;i]]][[-2]]~Table~{i,2,Length[s=#]}&

Try it online!

Perl 5, 42 39 + 1 (-a) = 40 bytes
say+(sort{$b-$a}@F[0..$_])[1]for 1..$#F

Try it online!

Swift 3, 67 bytes
func g(l:[Int]){print((1..<l.count).map{l[0...$0].sorted()[$0-1]})}

Test Suite.
Swift 3, 65 bytes
{l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]

Test Suite.

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]))

PHP, 53 bytes
for(;a&$n=$argv[++$i];rsort($a),print$a[1]._)$a[]=$n;

takes input from command line arguments. Output delimited, lead and trailed by semicola.
Run with -nr or try it online.
Yields a warning in PHP 7.1; replace a& with ""< to fix.
Or use for(;++$i<$argc;rsort($a),print$a[1]._)$a[]=$argv[$i]; (54 bytes)

Clojure, 56 bytes
#(for[i(drop 2(reductions conj[]%))](nth(sort-by - i)1))

Maybe there is a better way to generate those prefixes.

Mathematica 42 Bytes
Independently arrived at a answer very similar to @Jenny_mathy but 3 bytes shorter
Sort[#[[;;i]]][[-2]]~Table~{i,2,Length@#}&

Realized that the 1st running max takes only 15 bytes and two function calls!:
Max~FoldList~#&

This can be done so concisely because Max has the attributes Flat and OneIdentity but that's not true for RankedMax which would be the logical replacement.  Unfortunately defining attributes or modifying them on existing functions takes up way too many bytes, so the flattening must be done by other means.
All of the nth running maxes can be found in 48 bytes:
PadLeft[Sort/@Flatten/@FoldList[{##}&,{},#&@#]]&

JavaScript (ES6), 43 51 bytes
Edit: Added 8 bytes since numerical sorting is desired. :(
a=>a.map((_,b)=>a.slice(0,b+1).sort((a,b)=>b-a)[1])

Keeping this one here, though, as it is shorter providing one wants lexicographical ordering:
a=>a.map((_,b)=>a.slice(0,b+1).sort()[b-1])

Both expressions produce undefined for the first element.
Test code

const golfed =

a=>a.map((_,b)=>a.slice(0,b+1).sort((a,b)=>b-a)[1])

const inputs = [
  [1, 5, 2, 3, 5, 9, 5, 8],
  [1, 1, 2, 2, 3, 3, 4],
  [2, 1, 0, -1, 0, 1, 2]
];
console.log(inputs.map(x => golfed(x)));
// [ [ undefined, 1, 2, 3, 5, 5, 5, 8 ],
//   [ undefined, 1, 1, 2, 2, 3, 3 ],
//   [ undefined, 1, 1, 1, 1, 1, 2 ] ]

Note that I would have preferred to simply comment on the existing JS post if it were not for the reputation system.

Welcome to PPCG! I don't like the 50-rep comment threshold either, but I guess they need it to keep spammers from commenting. Anyway, I think this will fail if the input contains a double digit number such as 10, as .sort() sorts lexicographically by default (i.e. 1,10,100,11,12,13,...,2,20,21,...). You'd need to include (a,b)=>a-b or similar to get it to sort by number.

Thanks, @ETHproductions.  I've updated for numerical ordering, which means this is no longer good enough.  Oh, well.

Pyth, 15 bytes
FNr2hlQ@_S<QN1
Try it here: https://pyth.herokuapp.com/?code=FNr2hlQ%40_S%3CQN1&input=%5B1%2C+5%2C+2%2C+3%2C+5%2C+9%2C+5%2C+8%5D&debug=0
Explanation
FNr2hlQ - For loop with counter 2 <= N <= list length
@_S<QN1 - 2nd element when the first N elements of the list are sorted in ascending order and then reversed (sorted in descending order)

Octave, 51 bytes
@(a){[~,I]=cummax(a);a(I(2:end))=-inf;cummax(a)}{3}

- An arbitrary value returned for the first element.
Try it online!