Leetcode -Remove Element #27- Array

admin
By -
0

Photo by Tai Bui on Unsplash

Question:

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.

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.

Actual we need to  just return the modified array size at the end

Solution that  we used for it two pointer  and while loop


Description: In our solution, we first assign two pointers (or variables) to the indices i and j, where i starts at position 0. We then traverse the array using a for loop with the second pointer j, and use an if condition to find matching elements with a specific value k. For example, if k is 2, we check if the current element equals k. If we find a match, we swap it with the element at index i, since i is still one step behind j. This way, all elements that match the value k are moved to the front of the array. Afterward, we use a while loop to remove all occurrences of k from the array. Finally, we return the length of the modified array.

concepts: ARRAY, TWO POINTERS

e.g.

Steps:

nums = [0,1,2,2,3,0,4,2], val = 2

Swapping

nums = [2, 2, 2,0,1,3,0,4]

removed

nums = [0,1,3,0,4]


class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        j = 0

        for j in range(len(nums)):
            if nums[j] == val:
                nums[j], nums[i] = nums[i], nums[j]
                i = i + 1
            j = j + 1
       
        while val in nums:
            nums.remove(val)
       
        return len(nums)
       

Post a Comment

0Comments

Put Your Thought or Query Here

Post a Comment (0)