Solution (source code)

= Solution

<Fermat's principle> says that the travel time, or equivalently the <optical path length>, is stationary under small path variations at fixed endpoints. For a flat interface, let the ray cross at horizontal coordinate $x$, with source and detector at heights $h_1,h_2$ and horizontal separation $D$. Apart from $1/c$, its travel time is
$$
\mathcal L(x)=n_1\sqrt{h_1^2+x^2}+n_2\sqrt{h_2^2+(D-x)^2}.
$$
Setting $d\mathcal L/dx=0$ gives
$$
\frac{n_1x}{\sqrt{h_1^2+x^2}}=\frac{n_2(D-x)}{\sqrt{h_2^2+(D-x)^2}},\qquad
\boxed{n_1\sin i=n_2\sin r.}
$$
The angles are measured to the normal. This is <Snell's law>; “least time” is more generally a stationarity condition.