Update stack solution. The new one DOES takes O(n) time.