All questions
Medium2026-08-01

Implement Array.prototype.myFlat(depth)

Company
Freshworks
Role

Senior SDE (Fullstack)

Round

Round 2 (Frontend)

JavaScriptRecursionPrototype

Problem Statement

Implement a custom Array.prototype.myFlat(depth) method that works exactly like the native Array.prototype.flat().

The method should flatten a nested array up to the specified depth. If no depth is provided, default to 1. If depth is Infinity, flatten completely.

Constraint: Do NOT use the native .flat() method.

Constraints

  • Array can contain any type (numbers, strings, nested arrays, undefined, null)
  • 0 <= depth <= Infinity
  • Array can be nested to arbitrary depth
  • Must handle sparse arrays correctly

Example

[1, [2, [3, [4]]]].myFlat()
// [1, 2, [3, [4]]]  (depth = 1)

[1, [2, [3, [4]]]].myFlat(2)
// [1, 2, 3, [4]]

[1, [2, [3, [4]]]].myFlat(Infinity)
// [1, 2, 3, 4]

[1, , [2, , 3]].myFlat()
// [1, 2, 3]  (sparse slots removed)

Expected Implementation

Array.prototype.myFlat = function(depth = 1) {
  // Your implementation here
};

Follow-ups

  1. What are the risks of modifying Array.prototype? (prototype pollution)
  2. How would you implement this iteratively instead of recursively (to avoid stack overflow on deeply nested arrays)?
  3. What's the time and space complexity of your solution?
  4. How does the native Array.flat() handle non-array iterables inside the array?
馃

No solution provided

Think through it. That's how you build real interview muscle.

Share: