Majority element tle error

I AM GETTING TLE ERROR IN THIS CODE
#include
using namespace std;
#include<unordered_map>

int maj(int arr[] , int n)
{
unordered_map <int,int> m;
int s = n/2;

for(int i=0;i<n;i++)
{
    int v = arr[i];
    m[v]++;
    
    if(m[v] > s)
    return v;
}

return -1;

}

int main() {
int t;
cin>>t;

for(int i=0;i<t;i++)
{
    int n;
    cin>>n;
    int arr[n];
    
    for(int i=0;i<n;i++)
    cin>>arr[i];
    
    cout<<maj(arr,n)<<endl;

}
return 0;

}

BUT THIS CODE WORKS FINE PLEASE TELL WHY

#include
using namespace std;
#include<unordered_map>

int maj(int arr[] , int n)
{
unordered_map <int,int> m;
int s = n/2;

for(int i=0;i<n;i++)
{
    int v = arr[i];
    m[v]++;
}

for(auto i:m)
{
if(i.second>s)
{
return i.first;
}
}

return -1;

}

int main() {
int t;
cin>>t;

for(int i=0;i<t;i++)
{
    int n;
    cin>>n;
    int arr[n];
    
    for(int i=0;i<n;i++)
    cin>>arr[i];
    
    cout<<maj(arr,n)<<endl;

}
return 0;

}

Hi ANKIT, both the codes are workin’ fine.
But you can try changing the counter variable of the nested for loopS to j or something else instead of i because the parent loop also has i as the counter.
If you have doubt in a specific question then please share the question link over here. :slight_smile:

https://practice.geeksforgeeks.org/problems/majority-element/0

ur code is fine Ankit don’t think that there will be a problem