ByteDance Interview Question

Is there a faster way to implement this solution?