Suppose that $f : A \mapsto B$ is invertible with inverse $g : B \mapsto A$. Then $g \circ f = \operatorname{id}_A$ which means $\forall a \in A : g(f(a)) = a$. Let's take some $a_1, a_2 \in A$ with $f(a_1) = f(a_2)$; then $a_1 = g(f(a_1)) = g(f(a_2)) = a_2$.
The thing which I can't get is $g(f(a_1)) = g(f(a_2))$ equality. Where it comes form? Clearly, $a_1 = g(f(a_1))$ and $a_2 = g(f(a_2))$, but why it implies $a_1 = a_2$? Why can't they be non-equal, i.e. different, but mapped to the same $b = f(a_1) = f(a_2)$?
The only assumption I came up with is that having $b = f(a_1) = f(a_2)$ seems to violate mapping requirement for $g : B \mapsto A$, since it "maps" exactly the same $b$ twice: $(b, a_1)$ and $(b, a_2)$... nevertheless, still having a feeling like I do miss something important. Do I?
You've defined $a_1$ and $a_2$ so that $f(a_1)=f(a_2)$. Now, \begin{align}a_1=g(\underbrace{f(a_1)}_{=f(a_2)})=g(f(a_2))=a_2. \end{align}
This works because $g$ is defined as the inverse of $f$, so $g \circ f= \operatorname{id}_A$ is the identity function, and hence $g\circ f(a)=g(f(a))=a$ for any $a \in A$.
You are correct in stating that $g$ would not be a function if $a_1$ and $a_2$ were not equal, since this would mean that $g$ maps the same input, $f(a_1)=f(a_2)$ to two different outputs, $a_1$ and $a_2$.