I am solving a problem on InterviewBit and come across a question, here's link https://www.interviewbit.com/problems/diffk-ii/. When I have used c++ STL map to solve this problem, it shows me the message
Memory Limit Exceeded. Your submission didn't complete in the allocated memory limit. here's my code
int Solution::diffPossible(const vector<int> &A, int B) {
int n = A.size();
map< int , int > mp;
for(int i =0;i<n; i++)
mp[A[i]] = i;
int k = B;
for(int i =0; i<n; i++){
if(mp.find(A[i]+k) != mp.end() && mp[A[i]+k] != i){
return 1;
}
if(mp.find(A[i]-k) != mp.end() && mp[A[i]-k] != i){
return 1;
}
}
return 0;
}
and when I have replaced map by unorderd_map solution accepted. Here's code
int Solution::diffPossible(const vector<int> &A, int B) {
int n = A.size();
unordered_map< int , int > mp;
for(int i =0;i<n; i++)
mp[A[i]] = i;
int k = B;
for(int i =0; i<n; i++){
if(mp.find(A[i]+k) != mp.end() && mp[A[i]+k] != i){
return 1;
}
if(mp.find(A[i]-k) != mp.end() && mp[A[i]-k] != i){
return 1;
}
}
return 0;
}
It means map is taking more memory than unordered_map. Can anyone explain how this is happening? Why map is taking more memory space than unordered_map?