Nope, that's about as efficient as it gets. It's running in O(n) time. Really not much more you could ask. If there's anything you could optimize, it would be transforming a1 into a map, but that's optimization for memory, and it sounds like you want to speed things up intstead.