DEV Community 👩‍💻👨‍💻

Achilonu Chinwendu Faustina
Achilonu Chinwendu Faustina

Posted on

#14G10DaysCodeChallenge(Day2: Remove Element)

REMOVE OCCURRENES OF ELEMENT IN A GIVEN ARRAY

An array of nums and value was given to remove all instances of that value in-place, to return the new length. An instruction was given to allocate extra space for another array by modifying the input array in-place with 0(1) extra memory.
For example in input, nums = [4, 1, 2, 4] and val = 4;
expected output: nums = [1,2].

PROCEDURE

-Create indicator variable starting at zero (0) to keep track.

  • Iterate through every element in the array using the 'for loop'. If the current value is not equal 'val'; we set nums[indicator] to nums[i] and increment indicator.

For instance, in the given example above where we have the input, nums = [4, 1, 2, 4]. If we iterate through this, nums[0] = val, it is been skipped while we move to nums[1] which is not equal to 'val' making it to be qualified to what we want, it's been moved to the front because our indicator started with zero (0). Same is applicable to nums[2], it will also be shifted forward.

  • Return indicator.

Top comments (0)

🌚 Life is too short to browse without dark mode