Solution (source code)

= Solution

The <optional stopping theorem> at a <bounded stopping time> states that an <integrable> <martingale> $Z_n$ satisfies $\mathbb EZ_T=\mathbb EZ_0$ whenever $T\leq n$ for a fixed finite $n$. Apply this first to $S$ at $T=n\wedge\tau$. The <simple symmetric random walk> cannot cross an integer endpoint without hitting it, so
$$
a\leq S_{n\wedge\tau}\leq b,\qquad
\mathbb E S_{n\wedge\tau}=0.
$$
The preceding part gives $\tau<\infty$ <almost surely>, hence $S_{n\wedge\tau}\to S_\tau$ <almost surely>. The constant bound $C=\max\{-a,b\}$ permits the <dominated convergence theorem>, yielding $\mathbb ES_\tau=0$. Since $S_\tau$ is either $a$ or $b$, solving $ap+b(1-p)=0$ gives its full <probability distribution>:
$$
\boxed{\mathbb P(S_\tau=a)=\frac{b}{b-a},\qquad
\mathbb P(S_\tau=b)=\frac{-a}{b-a}.}
$$
Now let
$$
L_\tau=\sum_{k=0}^{\tau-1}\mathbf1_{\{S_k=0\}}.
$$
This counts the visit at time $0$, and excludes the exit time. Apply the same bounded-time <optional stopping theorem> to $M_n=|S_n|-L_n$. For each $n$ it gives
$$
\mathbb E L_{n\wedge\tau}=\mathbb E|S_{n\wedge\tau}|.
$$
The visit counts increase to $L_\tau$, so <monotone convergence> applies to the left. <Dominated convergence> applies to the right using $|S_{n\wedge\tau}|\leq C$. Consequently $L_\tau$ is an <integrable random variable> and
$$
\boxed{\mathbb E L_\tau=\mathbb E|S_\tau|
=(-a)\frac{b}{b-a}+b\frac{-a}{b-a}
=\frac{-2ab}{b-a}.}
$$
This is the origin case of <expected occupation before interval exit for a simple symmetric random walk>. The argument obtains <integrability> of the total occupation count before using any unbounded-time <optional stopping> for $M$, so it does not presuppose the <uniform integrability> asked about next. The endpoint <probabilities> also agree with the standard <gambler's ruin> calculation.<Probability: Theory and Examples (fifth edition) by Rick Durrett>[§4.8.1, Theorem 4.8.7(a), printed pp. 257–258: symmetric random-walk interval-exit probabilities]{ref}