Problem List
It’s basically compacting the valid elements to the front. This problem really made me think about when NOT to increment an index. Very tricky problem and the top solution made me realize I was dramatically overthinking it and coming from the wrong angle. The best solutions utilzed val != nums[i] where as I used a proper two pointer solution as long as val == nums[i].
O(n) Potentially visit every element once, even if some are swapped.O(1)Do everything in-place with a few counters — no extra memory needed.func removeElement(nums []int, val int) int {
c := 0
for i := 0; i <= len(nums)-1-c; i++ {
for nums[i] == val && i <= lch(nums,c) {
if i != lch(nums, c) {
nums[i], nums[lch(nums, c)] = nums[lch(nums, c)], nums[i]
}
c++
}
}
return lch(nums, c) + 1
}
func lch(n []int, c int) int {
return len(n) - 1 - c
}