First Repeating Element | Easy | Techgig
First Repeating Element | Easy | Techgig
C++ Solution
The first repeating element is the problem that comes under the Linear Search problem under the Algorithm section.
Linear Search or sequential search is a method for finding an element within a list. The algorithm works by selecting and checking each number sequentially until matched. A linear search runs in at the worst linear time and makes at most n comparisons, where n is the length of the list. If each element is equally likely to be searched, then the sequential search has an average case of (n+1)/2 comparisons, but the average case can be affected if the search probabilities for each element vary. The complexity of the linear search is as follows:

The basic linear search algorithm has the following steps:
Given a list L on n elements with values L0…Ln-1, and target value T, to find the index of the target T in the list L.
- Set i to 0.
- If Li = T, the search terminates successfully; return i.
- Increase i by 1.
- If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.
The question states that Given an array of integers, find the first repeating element in it. We need to find the number that occurs more than once and whose index of the first occurrence is smallest.
Input Format
A function with an integer array as arguments
Constraints
1 < N < 10⁵
1 < a[i] < 10⁵
Output Format
You need to return the first repeating element from the function.
Sample TestCase 1

Output

Time Limit(X): 1.00 sec(s) for each input.
Memory Limit: 512 MB
Source Limit: 100 KB
The below code suggest using two for loops, the first one to hold a value and the second one to iterate through the rest of the element.


The linear searching technique makes this much easier to understand for a beginner but there are ways to optimize this code. Can you try finding an optimized code for this problem?
Thank you for reading, have a delightful day.
Comments
Post a Comment