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:

 The first consecutive recurring number. Then answer of this will be 3.
 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.
func identifyFirstRecurringNumber(from array: [Int]) > Int {
// dictionary = [key : value]
var numberDict = [Int : Int]()
for num in array {
if let count = numberDict[num]
{
numberDict[num] = count + 1
return num
} else {
numberDict[num] = 1
}
}
//If there is no recurrent values in the hash
return 0
}
//Output = 1
In the function defined above, the for loop checks if there is any value against the key (num).
if let count = numberDict[num]
{
numberDict[num] = count + 1
return num
} else
{
numberDict[num] = 1
}
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.
func findFirstConsecutiveRecurrent(from array: [Int]) > Int {
var tempNumber = 0
for (i,c) in array.enumerated() {
tempNumber = c
if (tempNumber == array[i + 1]) {
return tempNumber
}
}
return 0
}
//output = 3
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.
Make sure to leave your feedback or suggestions in the comments down below.