AC

O(3n) solution