Member-only story
When we were a junior developer / entry level engineer while attending the interview, this one question could be faced by everyone
“How remove the duplicate elements from array”
After hearing/seeing this question all will start writing code like,
- Loop through the input array.
- Push the value to the output array if the same value not present in the output/second array
Am I correct?.
I guess most of us do the same.
In this case we may also face the time and space complexity issue. This kind of coding can be done by any programmer, or even freshers. So we should think smartly about having the best and optimal solution.
Here are the few ways!
Here is the in put array input = [1, 4, 2, 5, 'a', 1, 1, 1, 4, 5, 'a']
Way #1
input | [] # output [1, 4, 2, 5, "a"]
Way #2
input | input # output [1, 4, 2, 5, "a"]
Way #3
input & input # output [1, 4, 2, 5, "a"]
Way #4
input.uniq # output [1, 4, 2, 5, "a"]