27. Remove Element
Given an array and a val
remove all it occurrences in-place and return the number of remaining elements
if there are k
occurrence of val
change the array nums
such that the first k
elements of nums
contain the elements which are not equal to val
.
Intuition
An element shifts by the occurrence amount of
val
before it.
Approach
Start from beginning of the array tracking the occurrence of
val
(lets say its tracked byi
)Move an elements
i
steps forward in array if there arei
occurrence ofval
before it.
Complexity
Time complexity : $\text{O}(n)$
as we iterate the array only once
Space complexity : $\text{O}(1)$
No extra space is needed as everything is done in place
Code
Last updated