27 Remove Element

Problem Statement

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Instructions

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

  • Return k.

For the whole problem statement, please refer here.

Plans

  • Use a pointer to keep track of the position to place the next non-val element.

  • Loop through each element of the input array nums.

  • If the current element is not equal to val, place it at the pointer's position and increment the pointer.

  • At the end of the loop, the pointer will indicate how many elements are not equal to val, so return this count.

Solution

from typing import List

class Solution: 
    def removeElement(self, nums: List[int], val: int) -> int:
        # Pointer for the to place non-val elements
        k = 0

        # Traverse through each element in the array
        for i in range(len(nums)):
            # If the current element is not equal to val
            if nums[i] != val:
                # Place it at the k-th position
                nums[k] = nums[i]
                # Increment the k
                k += 1

        # The first k elements are now the desired elements
        return k

Explanation

  1. Initialization

    • Start by defining a variable k that will serve as a pointer to track the index of the next position whre a non-val element should be placed and initiaily, k is set to 0.

  2. Loop through the elements

    • Iterate over each element in the list nums using a for loop. The loop runs for the lenght of the list, allowing us to check each value.

  3. Condition to check

    • Inside the loop, check if the current element nums[i] is not equal to val. This condition is crucial as it determines whether we want to keep the current element or remove it.

  4. Place non-val elements

    • If the condition is true (meaning the element is not eqaul to val), assign the value of nums[i] to nums[k], effectively moving the non-val element to the front of the array.

  5. Increment pointer

    • After placing the element, we increment k to get ready for the next potential non-val element.

  6. Return the value of k

    • Once the loop completes, k will hold the count of the elements that are not equal to val. We return ths value to indicate how many elements should be considered in the updated array.

Last updated