Neat solution for 334 (runs in 0.3s).