Reduced the runtime from O(n log(n)) to O(n)