ByteDance interview question

Is there a faster way to implement this solution?