v3 time O(n) space O(n) Accepted

prev algorithm was complicated and error prone

changed to a very succinct and efficient algorithm

should memorize this one.