-
Notifications
You must be signed in to change notification settings - Fork 0
/
First_repeating_element.cpp
54 lines (44 loc) · 1.2 KB
/
First_repeating_element.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template in C++
class Solution {
public:
// Function to return the position of the first repeating element.
int firstRepeated(vector<int> &arr) {
unordered_map<int, int> mpp;
int firstIndex = -1;
for(int i = 0; i < arr.size(); i++)
{
if(mpp.find(arr[i]) != mpp.end())
{
if(firstIndex == -1 || firstIndex > mpp[arr[i]])
firstIndex = mpp[arr[i]];
}
else mpp[arr[i]] = i;
}
return firstIndex == -1 ? -1 : firstIndex+1;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input); // Read the entire line for the array elements
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution ob;
cout << ob.firstRepeated(arr) << endl;
}
return 0;
}
// } Driver Code Ends