27 Remove Element
Link to the problem: https://leetcode.com/problems/remove-element
Solution 1
I solved it using the swap idea and two pointers going from beginning and from the end. My solution is ok on speed and space, but there is a more elegant solution to this, when you actually swap the “not equal” elements and skip “equal”. See the Solution 2.
Code C#
Complexity
- Time O(n)
- Space O(1)
Solution 2
Idea is simple. You have two pointers running from the beginning. One being “fast” (for comparing) and one being “slow” (for keeping the values). You iterate over array with the slow pointer and if the value is not equal to the removal value, you put into slow pointer slot. Otherwise you skip.
Code C#
Complexity
- Time O(n)
- Space O(1)