add memory efficient solution by Jack Watson-Hamblin