Hacktoberfest - first 5 PR - part 2

2nd PR -  oddOccurrencesInArray 

The second issue is a puzzle containing pairs of characters. The task is to find one character that does not pair to any others. Quote from the author of the issue:
A non-empty array A consisting of integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. Write a function that, returns the value of the unpaired element.

The Solution 

For this kind of puzzle, using a collection to store unique numbers is the easiest way to achieve. The basic idea is, we take a number, check if it exists in the collection; if it does not, we put it into the collection; if it does, which means there is a pair, so we remove it from the collection. We will process all the numbers, then at the end the final number left in the collection is the one we need to find.

The Options

The problem is which type of collection we should take for this task. There are three options I thought about: plain object, array and map. Looking back at what we need, there are only two things, to check existing and to delete.
  • Array: for checking existence we can use findIndex(number), then we take the index into splice(index) to remove paired numbers.
  • Map: is pretty much the same as array, with has(number) and delete(number). Map is more than enough for what we need, since we only need to store values, we do not care about keys. However, one pro of map in this case is that we don't have to loop all the numbers just to find the existence of a number, so let's say a little bit more efficient.
  • Plain Object: now this turns to be the best choice because just like map, it doesn't require looping all items, and it is simple.

The Choice

Considering map and plain object are sort of similar, however map is more likely supposed to act as a collection, so my final decision was using map in the PR.

Link:

Comments

Popular Posts