# If $f$ takes every value at most $k$ times, then f is differentiable almost everywhere.

I am stuck at the following problem, I got in an old question paper (real analysis).

Let $$k>0$$ be a natural number and Let $$f$$ be a continuous function on real line such that $$f$$ takes any value at most $$k$$ times. Show that $$f$$ is differentiable almost everywhere.

My hunch is that we can divide the real line (except a few exceptional points) into intervals such that on each of those intervals $$f$$ is one-to-one and therefore monotonic and hence differentiable almost everywhere. But, I am not able to make this idea concrete. Any help would be appreciated.

It suffices to show that under the given condition, $$f$$ is locally of bounded variation, because then $$f$$ can be written as a difference of two continuous non-decreasing functions, which are differentiable almost everywhere by the Lebesgue's theorem for the differentiability of monotone functions. So the following proposition gives the result.
Proposition: If $$f$$ is continuous on $$[a,b]$$ and takes each value at most $$k$$ times, then it holds $$V_a^b(f) \le k (M-m)$$ where $$V_a^b(f)$$ is the total variation of $$f$$ on $$[a,b]$$, and $$\displaystyle M = \max_{x\in [a,b]}f(x)$$ and $$\displaystyle m = \min_{x\in [a,b]} f(x)$$.
Proof: Take any partition $$\Pi = \{a=x_0. We denote $$I_j = (f(x_{j-1}),f(x_{j}))$$ if $$f(x_{j-1}), or $$I_j = (f(x_{j}),f(x_{j-1}))$$ otherwise. Define $$F(y) = \sum_{j=1}^n 1_{\{y\in I_j\}} = \big[\#\text{ of j such that y belongs to I_j}\big].$$ Note that if $$y\in I_j$$, then by the Intermediate Value Theorem there exists $$t_j \in (x_{j-1},x_j)$$ such that $$f(t_j)= y$$. Since the number of such $$t_j$$ is at most $$k$$, this implies $$F(y)\le k$$ for each $$y$$. Because $$I_j \subset [m,M]$$ for each $$j$$, it follows that \begin{align*} \sum_{j=1}^n |f(x_j)-f(x_{j-1})| =& \sum_{j=1}^n \mathrm{len}(I_j)\\ =& \sum_{j=1}^n \int_{I_j}1\ \mathrm dy \\ =&\sum_{j=1}^n \int_m^M 1_{\{ y\in I_j\}} \mathrm dy\\ =& \int_m^M F(y) \mathrm dy \\ \le&\ k(M-m). \end{align*} And this implies $$V_a^b(f) = \sup_{\Pi} \sum_{j=1}^n |f(x_j)-f(x_{j-1})| \le k(M-m).$$