Algorithm by kaikeba