F5 interview question

Technical question from leet code. 1 medium and 1 hard problem