Pair of Roses problem

Problem link:
https://online.codingblocks.com/app/player/115374/content/73637/5064/code-challenge

Code link:

Can you please tell why I am getting error?

@mgfags
you should be getting wrong answer because after taking input in the map you are checking just value not index.
for eg input :-
1
40
80
here target is 80 and only one element is present which is 40.

so in this case your code will give answer as 40 and 40, which is not a possible pair.
So what you should here do is don’t save just mp[arr[i]]=1 instead save it as something mp[arr[i]]++. so that you also have the index for that sum.

so that while checking for min difference pair if you find out abs(target-arr[i]) is present in the map and then also made a check if that is equal to arr[i] itself then their should be more that one count of it.
I think if you understood it then you can do the changes in the code.
But feel free to ask if you face any difficulty in implementation or have a look at modified code https://ide.codingblocks.com/s/261198

Just to knowledge(if you don’t know):- There is one more approach to this problem using 2 pointers after sorting the array which takes O(1) extra space in same O(nlogn) time complexity, so just have that in your mind also in case of interviews that can be useful.

Please mark the doubt as resolved if it is solved now.

Thanks for you help.

1 Like