Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

27. Remove Element

ArrayTwo Pointers

Explanation

To solve this problem, we can use a two-pointer approach where one pointer iterates through the array while the other pointer keeps track of the next position to overwrite when the element needs to be removed. We iterate through the array, and whenever we encounter an element equal to the given value, we skip it. If the element is not equal to the given value, we copy it to the position indicated by the second pointer. This way, we effectively remove the specified value from the array in-place.

Algorithm

  1. Initialize two pointers i and k at the start of the array.
  2. Iterate through the array using pointer i.
  3. If nums[i] is equal to val, skip this element.
  4. If nums[i] is not equal to val, copy nums[i] to nums[k] and increment k.
  5. Continue this process until i reaches the end of the array.
  6. Return the value of k as the length of the modified array.

Time Complexity

The time complexity of this algorithm is O(n), where n is the number of elements in the input array nums.

Space Complexity

The algorithm has a space complexity of O(1) as it modifies the input array in-place without using any extra space.

class Solution {
    public int removeElement(int[] nums, int val) {
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[k] = nums[i];
                k++;
            }
        }
        return k;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.