v2 time O(n) space O(1) Accepted

in v1 didn't double check possible null pointer exception when "optimizing" code