0

I'm trying to write a program for a given array and a value, to remove all instances of that value in place and return the new length.

Example: Given input array nums = [3,2,2,3], val = 3

It should return length = 2, with the first two elements of nums being 2.

Here is my code:

Code 1:

def removeElement(self, nums, val):
    """
    :type nums: List[int]
    :type val: int
    :rtype: int
    """
    i = 0
    j = len(nums) - 1

    while i <= j:
        while i <= j and nums[j] != val:
            j -= 1

        while i <= j and nums[i] == val:
            i += 1

        if i <= j:
            nums[i], nums[j] = nums[j], nums[i]

    return len(nums[i:])

This returns the array slice in reverse order.

Input:
[3,2,2,3]
3 
Output: [3,3] 
Expected: [2,2]

However, if I make slight modifications at the end of the code 1, it gives me the correct output:

    nums[:] = nums[i:]
    return len(nums[i:])

Code 2:

def removeElement(self, nums, val):
    """
    :type nums: List[int]
    :type val: int
    :rtype: int
    """
    i = 0
    j = len(nums) - 1

    while i <= j:
        while i <= j and nums[j] != val:
            j -= 1

        while i <= j and nums[i] == val:
            i += 1

        if i <= j:
            nums[i], nums[j] = nums[j], nums[i]

    nums[:] = nums[i:]
    return len(nums)

I cant figure out why my code 1 doesnt work. Could someone help me understand why slice doesnt work as expected?

2
  • 1
    I don't think either approach works, unless you have some restriction on the input that you haven't mentioned. Commented Dec 20, 2016 at 5:44
  • The strange thing is that I ran your code1 and it worked as expected, i.e. with input [3,2,2,3] returns [2,2] and length 2. Commented Dec 20, 2016 at 6:10

2 Answers 2

2

This would do what you intend ("... remove all instances of that value in place and return the new length"):

def remove_element(nums, val):
    nums[:] = [x for x in nums if x != val]
    return len(nums)

Test:

nums = [3, 2, 2, 3]
val = 3
print(remove_element(nums, val))
print(nums)

Output:

2
[2, 2]
Sign up to request clarification or add additional context in comments.

Comments

0

Your first example works.

When you slice a new list is created. So in your first code sample you are creating a new list at the end containing the correct result, but never returning it.

In your second code example you are assigning the newly created list to the original list and are hence able to access the final result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.