Skip to the solution
EasyDSAAsked in 20247 min read

Remove elements in-place

714 views

The problem

Problem, as an interviewer would state it: "Implement removeElement(arr, val) — removing every occurrence of val from the array IN PLACE, returning the new, real length, matching the well-known LeetCode-27-style contract."

Examples:

Code
const arr = [3,2,2,3];
removeElement(arr, 3); // returns 2, arr's first 2 elements are now [2,2]

Clarifying questions expected:

  • Does the ORDER of the remaining elements need to be preserved, or is any final order of the survivors acceptable?
  • Should this genuinely allocate a new array, or must it mutate the original array in place (matching the real LeetCode-27 convention)?
  • What is the real, correct meaning of the RETURNED length — is the caller expected to only look at the first k elements of the mutated array afterward?

Code / implementation expected: Yes — real, direct proof of correct in-place mutation (same array reference, with .length itself updated), returning the correct new length, matching real LeetCode-27 semantics.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: removeElement() correctly removes every occurrence of a target value in place, matching real LeetCode-27 semantics with a genuinely updated array length

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 33 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement Array.prototype.some() and every() From Scratch

Continue