The general problem is: let $A\in M_{m,m},B\in M_{n,n}$. Do there exist $X\in M_{m,n},Y\in M_{n,m}$ s.t. $XY=A,YX=B$ ? The NS condition is given by a result due to Flanders; cf. for example the free access paper
https://www.sciencedirect.com/science/article/pii/0024379568900475
We consider the (generic) case when $m\geq n$ and $B$ is generic (then its eigenvalues $(\lambda_i)$ are non-zero and distinct and $B$ is diagonalizable invertible); thus, NECESSARILY, $spectrum(A)=\{spectrum(B),0_{m-n}\}$ and the eigenvalue $0$ of $A$ is semi simple; then $A=PDP^{-1},B=Q\Delta Q^{-1}$ where $D,\Delta$ are diagonal.
Let $X'=P^{-1}XQ,Y'=Q^{-1}YP$; then $X'Y'=D,Y'X'=\Delta$ and we may assume that $A=diag(0_{m-n},(\lambda_i)_i),B=diag((\lambda_i)_i)$. Necessarily $rank(X)=rank(Y)=n$ and $X,Y$ are in the form $X=\begin{pmatrix}0\\U\end{pmatrix},Y=\begin{pmatrix}0&V\end{pmatrix}$ where the $n\times n$ invertible matrices $U,V$ satisfy $UV=VU=diag((\lambda_i)_i)$. Finally $U,V$ are diagonal matrices $U=diag(u_i),V=diag(v_i)$ s.t. $u_iv_i=\lambda_i$.
Note that $U$ depends on $n$ parameters and, roughly speaking, the set of solutions in $U$ is almost a vector space; therefore, the set of solutions in $X$ too. Clearly, $X$ is a solution of the linear equation $(*)$ $AX=XB$; one can see that the set of solutions of the equation $(*)$ is a vector space of dimension $n$. Then it's useless to diagonalize $A,B$; it suffices to find the solutions with rank $n$ of $(*)$; in a second step, the linear system in $Y$: $XY=A,YX=B$ has a unique solution.