So I was reading an article where the person was talking about the internship interview process and in it, the person was asked 2 algorithm related questions. I decided to solve them myself and see how I would approach such a problem. Here is the problem — you are given an array of integers [1,2,1,3,3] and you want to find:
1. The first consecutive recurring number. Then answer of this will be 3. 2. The first recurring number in the array. The answer of this will be 1.
The first problem was solved by using a simple hash table or a dictionary. The key of that hash map will be the integers in the given array and the value will be the count or number of times the integer occurs.
In the function defined above, the for loop checks if there is any value against the key (num).
If the value is nil then it assigns 1 to it. Otherwise, if the value is already present it increments its value by 1.
The moment it finds another value against the same key, it increments the count and returns that num.
2. I solved the second problem using simple iteration. There is a recursive solution as well for it which I will try later or you can do it and post it in the comments below :)
The second question states to find the first consecutive recurring numbers in the array. In this question I simply used a for loop to iterate through the arrays and compared the present number with the next number in the array.
The array is passed and in for loop I am using array.enumerated() to get the element “c” and it’s index “i”.
Then it’s simply a matter of comparing the current number with the next in the array by using array[i + 1] and returning the number if its equal.