The One with Remove Element

I haven't written code in a while — and when I say this, I mean long enough that I had to Google the syntax for almost every line. Still, I didn’t fall into the tutorial loop.
I started with an easy problem, just so I wouldn’t feel overwhelmed — and yet I still got tired. I had to re-read the question a few times to really understand what I was supposed to do. My manager always tells us to thoroughly read the problem before jumping into code. I think it’s good that I followed his advice this time, because my initial understanding was totally off.
Anyway, I took a book and wrote down what the problem wanted. I always start by thinking how a human would solve the problem first, and then I think about how the programming language can do the same. That approach really helps me build a good understanding of the task.
🧩 The Problem
Given an array of integers and a value val
, remove all instances of val
in-place and return the new length of the array. The elements beyond the returned length can be ignored.
Since I didn’t remember much Go, and Go doesn't have a pop()
function (yes, I Googled it), I found out that you can use slice operations instead. So after checking the syntax, I decided to go with the append()
+ slicing approach to remove elements.
I got syntax errors, and even a "slice bounds out of range" panic. But I kept going, and finally submitted a solution that beats 100% in runtime. 🎉
I also explored other solutions that performed better in terms of memory, just to see different perspectives on solving the same problem. Found one that used very little memory — and learned something new from it.
✨ Takeaway
If a problem has specific clauses or phrases, especially about how the solution will be evaluated, I should go deep into that. Those aren’t just instructions — they’re clues. They hint at how to solve the problem in a smarter way.
For example, in this problem, the line
“The elements beyond the returned length can be ignored” was something I completely ignored at first. But that sentence was actually the key to writing a more optimised solution.
I focused too much on actually removing the elements. But a better and more efficient approach lies in simply overwriting the array and ignoring everything after the new length k. That one line changed the entire perspective of the solution
Anyway, this felt really good — to do something and complete it on my own. More power to me!
Subscribe to my newsletter
Read articles from cia directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by