Added better algorithm - using cache