Merged three O(n) cycles into one