# $M$ is disconnected iff $\exists f$ s.t. $f^{-1}(\{0\})=\emptyset$ while $f^{-1}((-\infty,0))\ne\emptyset$ and $f^{-1}((0,\infty))\ne\emptyset$

Prove that $M$ is disconnected iff there is a continuous function $f: M\to \mathbb{R}$ such that $f^{-1}(\{0\})=\emptyset$ while $f^{-1}((-\infty,0))\ne \emptyset$ and $f^{-1}((0,\infty))\ne \emptyset$.

My attempt:

$(\Rightarrow)$ I know there exists a function defined by $f(x)=d(x,A)-d(x,B)$ satisfying the conditions. I have proved this part.

$(\Leftarrow)$

$f^{-1}=((-\infty,0))\ne \emptyset$ $\Rightarrow \exists X_1 \subset M$ such that $f(X_1)=(-\infty,0).$ Similarly, $\exists X_2 \subset M$ such that $f(X_1)=(0,\infty)$. $X_1$ and $X_2$ are disjoint and $X_1 \cup X_2=M$. Both $(-\infty,0)$ and $(0,\infty)$ are open in $\mathbb{R}$. So, $X_1$ and $X_2$ are open in M. So, M is disconnected.

I think there is something wrong in my proof because I don't use $f^{-1}(\{0\})\ne \emptyset.$ Where is my mistake?

You did use the fact $f^{-1}[\{0\}]=\emptyset$ when saying $X_1 \cup X_2 = M$.
$X_1 \cup X_2 \cup \emptyset = f^{-1}[(-\infty,0)] \cup f^{-1}[(0,\infty)] \cup f^{-1}[\{0\}] = f^{-1}[\mathbb{R}]=M$.
Suppose $(M,\tau)$ is a disconnected topological space. Choose non-empty, disjoint $A, B \in \tau$, whose union is $M$. Define $f:M\rightarrow\mathbb{R}$ as follows. For every $x \in M$, $$f(x) := \begin{cases} -1 &, x \in A,\\ 1 &, x \in B. \end{cases}$$ Then $f$ satisfies the requirements.
Conversely, suppose $f:M\rightarrow\mathbb{R}$ satisfies the conditions stipulated in the question. Define \begin{align} A &:= f^{-1}\big((-\infty,0)\big), \\ B &:= f^{-1}\big((0,\infty)\big). \end{align} Then $A, B$ are non-empty, disjoint open sets, whose union is $M$.