# necessary and sufficient condition for injectiveness and surjectiveness of a function

Let $f: A→B$ be a function between non-empty sets $A, B.$

(a) Prove that f is injective if and only if there exists a function $g: B→A$ such that $g◦f = idA$, where $idA: A→A,$ is the identity function.

(b) Prove that $f$ is surjective if and only if there exists a function $g: B→A$ such that $f◦g = idB.$

my concern is since $f$ is not surjective then how can we define $g=f^{-1}$ taking domain as whole $B$? thanks for any suggestion on existance of such $g$

With an injective non-surjective $f$ we can still define a $g : B \to A$ as $$g(y) = \begin{cases} x \text{ such that } f(x) = y && \text{if } \exists x . f(x) =y \\ z && \text{otherwise} \end{cases}$$ where z is some element of A. In this construction $g \circ f = id_{A}$ because we will never run into a case where $g$ is called for an element that isn't in the image of $f$.
The question doesn't say $g$ needs to be inverse of $f$. The point is that you just require some $g$ to work, and this doesn't have to be inverse of $f$.
For a) If $f$ is injective, you can define $g:B\to A$ by $g(f(x))=x$ whenver $x\in A$, and if $y\in B\setminus f(A)$ then just pick some element of $a$ and $g(y)=a$. Conversely if such $g$ exists then $f$ cannot be non-injective.
You're absolutely correct that if $f$ is not surjective, then there is no $g = f^{-1}$ with domain all of $B$. But neither (a) nor (b) is trying to do that. In (a), $g$ will only need to be $f^{-1}$ on the range of $f$; elsewhere it can be defined differently. In (b), we don't need to find a $g$ if $f$ is not surjective - in fact, the statement is that there isn't one.