Leetcode 27 Solution

This article provides solution to leetcode question 27 (remove-element)

https://leetcode.com/problems/remove-element

Thinking Process

Same logic as remove-duplicates-from-sorted-array. Use two pointers to walk the array, and fill up the array inplace.

Time & Space Complexity

Assuming there are N elements in the array:

  • Time complexity: O(N)
  • Space complexity: O(1)

Solution

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int l = 0;
        int r = 0;
        int n = nums.size();

        while (r < n)
        {
            if (nums[r] == val)
                r++;
            else
            {
                nums[l++] = nums[r++];
            }
        }

        return l;
    }
};