how to prove this ( about surjective functions and inverse functions) I  was making excercises for an upcoming exam and when trying to make this one I really got stuck.
The question is:
Prove that a function $f$ from $X$ to $Y$ is surjective if and only if there exists a function $g$ from $Y$ to $X$ with $g$ after $f$ is the unit function (the function that maps every $x$ on $x$).
My thoughts directly went to the inverse function but than I started having doubts because if the domain is bigger than the co-domain the inverse function would have to have more than one value for every input and than g wouldn't be a function.
My second thought was the same but with a reduced domain so that f becomes bijective but I do't think thats allowed in this question.
Does someone know a way to solve/proof this question?

Suppose that $f$ is surjective. We want to define a function $g: Y \to X$ such that $f \circ g = \operatorname{Id}_Y$. Well, given $y \in Y$, we know that there exists at least one $x \in X$ such that $f(x) = y$. So define $g$ by choosing exactly one such $x$: that is, define $g$ by $g(y) = x$ for each $y \in Y$, where $x$ is an arbitrarily chosen element of $X$ such that $f(x) = y$ (and such an $x$ is guaranteed to exist because $f$ is surjective). In that case, the composition $g \circ f$ acts on each $y \in Y$ by $(f \circ g)(y) = f(g(y))= y$ by our construction of $g$, and hence the composition satisfies the desired property.
Conversely, suppose there exists $g: Y \to X$ such that $f \circ g = \operatorname{Id}_Y$. We want to prove $f$ is surjective, i.e to each $y \in Y$ we want to find $x \in X$ such that $f(x) = y$. Well, since $f \circ g = \operatorname{Id}_Y$, then for each $y \in Y$, $f(g(y)) = y$. So letting $x = g(y)$ we get $f(x) = y$, as desired. Therefore $f$ is surjective.
