9Z's solution added. Space is o(n^2) though.