linear time using stack