Derivation (gambling mean time recurrence relation)

For $p=1/2$, look for particular solution $\tau_x = Cx_2$: $$ Cx^2 = 1 + \frac12C(x^2+2x+1) + \frac12 C(x^2-2x+1) $$ so $C=-1$. Hence a general solution is $$ \tau_x = Ax+B-x^2 $$ and using the boundary conditions we have $$ \tau_x = x(a-x). $$

For $p\neq 1/2$, look for particular solution $\tau_x = Cx$: $$ Cx = 1 + pC(x+1) + qC(x-1) $$ so $C=1/(q-p)$. The general solution is $$\tau_x = A+B\Big(\frac qp\Big)^x + \frac{x}{q-p}. $$ Then apply the boundary conditions: $$ \begin{cases} 0&=\tau_0=A+B \\ 0 &=\tau_a = A+B\Big(\dfrac qp\Big)^a + \dfrac{a}{q-p} \end{cases} \implies B=-A= \frac{a}{q-p}\frac{1}{1-(q/p)^a} $$ hence $$ \tau_x = \frac{x}{q-p} - \frac{a}{q-p}\frac{(q/p)^x - 1}{(q/p)^a - 1}. $$