Skip to content

Latest commit

 

History

History
42 lines (38 loc) · 972 Bytes

File metadata and controls

42 lines (38 loc) · 972 Bytes

Screen Shot 2022-09-05 at 18 10 40

Screen Shot 2022-09-05 at 18 10 50

C++

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int ptr = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] != val) {
                nums[ptr] = nums[i];
                ptr++;
            }
        }
        return ptr;
    }
};

JS

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    let i = 0;
    for(let j = 0; j < nums.length; j++) {
        if(nums[j] !== val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
};

TC: O(n)
SC: O(1)