I've just begun a #10-day coding challenge organized by Ingressive4Good. Today is Day2 and I'll be sharing my thoughts on how i was able to tackle Day2 problem. so lets get to it!
Question - 27. Remove Element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Example
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).
My experience
It wasn't really as tough as yesterday's own, Probably due to the fact that it was sort of an extension of the Day1 task. So i went through it like a gentle man ๐๐
As usual i started my approach with javascript (i prefer php btw). My approach to the solution was directed towards using loops and assigning the value that is not required in a new array. Next i sorted the inputted array and then return the length of the value of the new array .
And that was it!
confused?
Alright let me make it clear. Here's what i did again,
- create a new array
- run a loop to through the whole element in the input array -check if the item in each of the element equals the given value while in the array -if !true add to new array
- else //you know what to do ๐ -sort and return values.
After all of this, I discovered that my solution consumed a lot of RAM. For a time, I tried optimizing it but it didn't seem to work. Then I decided to rebuild it in PHP to see if it would produce better results. That, too, was a failure.
Long story shot
I went back to js, did a little more optimization and submitted and somehow , that did the trick.
Conclusion
Well that's all for now, if this blog post was any useful to you , Please give it a thumbs up.