MathWorks interview question

Hackerrank - 1Medium, 1 Medium-Hard LC question