Problem List

Remove Element

May 31, 2025Go two-pointer, arrayeasy

Problem

Approach

Edge Cases

Reflections

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].

Performance

Complexity

Go Solution
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
}
LeetCode Problem Link