better algorithm