import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i =0;i<n;i++){
arr[i] = sc.nextInt();
}
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<n;i++){
map.put(arr[i],-1);
}
int count = 0;
for(int i = 0;i<n;i++){
if(map.containsKey(arr[i])){
map.put(arr[i],count);
count++;
}
else{
map.put(arr[i],count);
count++;
}
}
ArrayList list = new ArrayList();
Set<Map.Entry<Integer,Integer>> entrySet = map.entrySet();
for(Map.Entry<Integer,Integer> entry : entrySet){
System.out.println(entry.getValue());
}
}
}
What is the problem with my code only one of my test case is running ok
hi, your logic is incorrect. as you can see inside your for loop (used for inserting data into map), if and else both have same body, so if condition is useless.
Now if you observe the hashcode carefully… its actually assigning a whole number to each unique array element in order and if a number is repeated ,its last occurrence is preferred.
for eg. for array: 2 34 5 32 5 2 34
output: consider unique elements of array by taking last occurrence of repeating elements
array would become: 32 5 2 34 and then assign whole numbers to these elements i.e. 32 - 0 , 5-1, 2-2, 34-3.
output : 32 5 2 34
you can solve this problem by multiple ways. one simple way is
- traverse array in reverse direction, add elements in a list and ignore elements if they already encountered(maintain a set of elements visited)
2.list will contain unique elements. if you traverse this list in reverse, this will be your answer.
Thanks.
can u provide me the code for this problem
Its not recommended to provide you the code. try to do it yourself. I have given you the exact algorithm , try to convert it into java code