Easy C++ using only Unordered_maps, all improvisations are welcome!


#1

vector Solution::solve(vector &A)
{
unordered_map<int,int> hash;//contains val , index
vector ans = A;
for(int i=0;i<A.size();i++)
{
if(hash.find(A[i]) == hash.end())
{
hash[A[i]] = i;//storing index
}
else
{
int val = A[i];
int index = hash[val];
hash[val] = i;
ans[index] = val + 1;
hash[val+1] = index;
}
}
return ans;
}


#2

i think your approach is wrong
for case: 1 1 1 2
output should be 3 2 1 2
but your solution gives 2 3 1 2


#3

@farhan-asif
I agree with you, however it passed all test cases on Interview bit

Anway I wrote another logic below: (It fails multiple test cases here, any thoughts on this?)
vector Solution::solve(vector &A)
{
unordered_map<int,int> map;
for(int i=0;i<A.size();i++)
{
if(map.count(A[i]) == 0)
{
map[A[i]] = i;
}
else
{
int index = map[A[i]];
A[index]++;
map[A[i]] = i;
if(map.count(A[index]) == 0)
map[A[index]] = index;
}
}
return A;
}