ByteDance interview question

1 leetcode medium, with extended question