Unlock Hasing and Tries

import java.util.*;
public class Unlock {

public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int N = sc.nextInt();
	int k = sc.nextInt();
	int[] arr = new int[N];
	HashMap<Integer,Integer> m = new HashMap<>();
	int count = 0;
	for(int i=0;i<N;i++) {
		arr[i] = sc.nextInt();
		m.put(arr[i], i);
	}
	
	for(int i=N;i>=1;i--) {
		if (k>0){
		int init = m.get(i);
		int best = N-i;
		
		

		if(init != best) {
		m.put(i, best);
		int element = arr[best];
		m.put(element, init);
		swap(arr[best],arr[init]);
		k--;
	}
		
		
}
	}
	for(int i=0;i<N;i++) {
		System.out.print(arr[i]+" ");
	}
	
}


public static void swap(int i,int j) {
	int temp;
	 temp = i;
	 i = j;
	 j = temp;
	
}

}

//sir im getting wrong output please suggest any changes

@Siddharth_sharma1808,
Implement this approach:

  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.