Hone logo
Hone
Problems

Remove Element

Given an array and a value, remove all instances of that value in-place such that the relative order of the remaining elements is not changed. The function should return the new length of the array after removal. It is not necessary to consider the elements beyond the new length.

Problem Description

You are tasked with modifying an array by removing all occurrences of a specific target value. This operation needs to be performed "in-place," meaning you should modify the given array directly without allocating extra space for another array. The order of the elements that are not equal to the target value should be preserved. After the removal process, the function should return the number of elements remaining in the array. The contents of the array beyond the returned length are irrelevant.

Key Requirements:

  • Modify the input array in-place.
  • Remove all instances of the target value.
  • Preserve the relative order of the elements that are not equal to target.
  • Return the new length of the modified array.

Expected Behavior: The array will be modified such that the first k elements (where k is the returned length) are the elements that were not equal to target, in their original relative order. The elements from index k onwards can be anything.

Edge Cases to Consider:

  • An empty input array.
  • An array where all elements are equal to the target value.
  • An array where no elements are equal to the target value.
  • The target value appearing at the beginning, end, or in the middle of the array.

Examples

Example 1:

Input: nums = [3, 2, 2, 3], target = 3
Output: 2
Explanation: The function should return 2, and the first two elements of nums should be [2, 2]. The elements beyond the returned length do not matter.

Example 2:

Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], target = 2
Output: 5
Explanation: The function should return 5, and the first five elements of nums should be [0, 1, 3, 0, 4] (order preserved). The elements beyond the returned length do not matter.

Example 3:

Input: nums = [], target = 1
Output: 0
Explanation: An empty array remains empty, and the length is 0.

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= target <= 100
  • The operation must be performed in-place.
  • The time complexity should ideally be O(n), where n is the length of the array.

Notes

Think about how you can iterate through the array and decide which elements to keep and where to place them. Since the order of the remaining elements matters, you might need a way to distinguish between elements that should be moved and elements that should be kept in their current relative positions.

Loading editor...
plaintext