Are there always matrices $X$ and $Y$ such that $XY=A$ and $YX=B$? Fix a natural number $n$ and let $A,B\in\mathbb{C}^{n\times n}$. Are there matrices $X,Y\in\mathbb{C}^{n\times n}$ such that $XY=A$ and that $YX=B$? A necessary condition for that to happen is that $A$ and $B$ have the same characteristic polynomials. But this condition is not sufficient: if $A=\operatorname{Id}_n$, then $XY=A\implies YX=A$.
So, my question is: are there necessary and sufficient conditions about $A$ and $B$ so that the problem has a solution?
 A: If $A$ and $B$ are non-singular, $X$ and $Y$ have to be too. Then $A=XY$
and $B=YX$ for some $X$, $Y$ iff $A$ and $B$ are conjugate in $\text{GL}_2(\Bbb C)$. But there are nonsingular matrices $A$, $B$ which
have the same characteristic polynomial but are not conjugate. For a trivial example, take $A=I$ and $B=\pmatrix{1&1\\0&1}$.
A: 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.
