How do i swap the values of the hashmap in this question?

swapping the values of the hashmap

@lousybrick,
you can swap the values in a hashmap like we swap values in 2 variables.

                int temp=map.get(idx);
                map.put(idx, val); //just update the value at the index. And you can store the original value in temp
  

I’m still not able to figure out how do i add the old index to the other key and also how do i print out the values in the order of an array ? I’ve used Set<Map.Entry> but I’m always getting a sorted output.
Here’s my code - https://ide.codingblocks.com/s/235049

@lousybrick,
https://ide.codingblocks.com/s/235113 corrected code.

Algo:

  1. Create the map by filling the number as the key and the index at which it is present as the value
  2. Iterate over the whole array.
  3. For element at a particular index m we will check if it is present at its best spot or not.
  4. The best spot of any number num is the N-num index of the array.
  5. If the number is not present at its best spot then we will swap the number with element present at that spot.
  6. As we have stored the index of every element in the map we can easily retrieve that from the map to get the swap done.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.