Consider the regression problem where we have $m$ measurements of the dependent variable and a model with $n$ degrees of freedom, where $m>n$. We can write the dependent variable measurements in a vector $\mathbf{y}$ (size $m\times 1$) and the model parameters in a vector $\mathbf{x}$ (size $n\times 1$), and arrange the independent measurements appropriately in a matrix $\mathbf{A}$ (size $m\times n$). The problem is now to choose $\mathbf{x}$ such that $\mathbf{y}$ is represented as closely as possible by $\mathbf{A}\mathbf{x}$. The most common way of quantifying "as closely as possible" is in the least-squares sense. We write: $$ E = \left(\mathbf{y} - \mathbf{A}\mathbf{x}\right)^T\left(\mathbf{y} - \mathbf{A}\mathbf{x}\right) \tag{1} $$
By taking the derivative of $E$ wrt $\mathbf{x}$ and setting it to zero, we end up with the least-squares solution:
$$ \mathbf{x}=\left(\mathbf{A}^T \mathbf{A}\right)^{-1} \mathbf{A} \mathbf{y} \tag{2} $$
I once had a professor show me a hacky way to have to neither remember this formula, nor do the tedious derivation in an exam situation. He was very clear that it was a hack and that I should never use it as a serious derivation. It goes as follows - start out by writing:
$$ \mathbf{A}\mathbf{x} = \mathbf{y} \tag{3} $$
Observe that we cannot solve this equation by taking the inverse of $\mathbf{A}$ because this is not a square matrix. No problem! - multiply each side by $A^T$ (size $n\times m$) to get: $$ \left(\mathbf{A}^T\mathbf{A}\right) \mathbf{x} = \mathbf{A}^T \mathbf{y} \tag{4} $$ Now $A^T A$ is a square matrix (size $n\times n$), which means it's (potentially) invertible. Multiply each side by $\left(\mathbf{A}^T \mathbf{A}\right)^{-1}$ to get: $$ \mathbf{x} = \left(\mathbf{A}^T \mathbf{A}\right)^{-1} \mathbf{A} \mathbf{y} \tag{5} $$
We get the right result, in the least-squares sense! Of course the hack is that, in general, Eq. (3) is not true to begin with; it is an inconsistent equation with no solution.
My question is: Is it just pure coincidence that this hack works in this particular case? Or is there perhaps a deeper reason? Maybe an insight as to why it leads to the least-squares solution as opposed to other one? Thank you!