Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given a linked list(need not be sorted) with duplicates, remove all duplicates, such that only the first occurrence of each element must remain in the LL, and return the head.
  3.  
  4. Input format
  5. There are 2 lines of input
  6.  
  7. First-line contains N, the number of elements in the linked list.
  8.  
  9. The next line contains N space-separated integers, elements of the linked list.
  10.  
  11. Output format
  12. Print the linked list after removing duplicates. Only the first occurrence of an element should be present in the list.
  13.  
  14. Function definition
  15. The function you have to complete accepts the head as an argument. You will make the necessary changes, and return the head.
  16.  
  17. Sample Input 1
  18. 5
  19.  
  20. 1 2 2 3 3
  21.  
  22. Sample Output 1
  23. 1 2 3
  24.  
  25. Explanation 1
  26. Node 2 and 3 have 2 occurrences each.
  27.  
  28. Sample Input 2
  29. 5
  30.  
  31. 3 1 3 1 4
  32.  
  33. Sample Output 2
  34. 3 1 4
  35.  
  36. Explanation 1
  37. The first occurrence of nodes 3 and 1 remains in the list and 4 has no duplicates.
  38.  
  39. Constraints
  40. 0 <= Number of nodes <= 10^5
  41.  
  42. -10^9 <= ListNode.val <= 10^9
  43. */
  44.  
  45. /*
  46. class ListNode{
  47.     constructor(val){
  48.         this.val = val;
  49.         this.next = null;
  50.     }
  51. */
  52. /**
  53.  * @param {ListNode} head
  54.  * @return {ListNode}
  55.  */
  56. function removeDuplicates(head) {
  57.       let currentNode=head;
  58.       let finalList=null;
  59.       let newHead=null
  60.       let mp = new Map();
  61.       while(currentNode!=null){
  62.             if(!mp.has(currentNode.val)){
  63.                   mp.set(currentNode.val,currentNode);
  64.             }
  65.             currentNode=currentNode.next;
  66.       }
  67.       currentNode=head;
  68.       while(currentNode!=null){
  69.             if(mp.has(currentNode.val)){
  70.                   if(mp.get(currentNode.val)==currentNode){
  71.                         if(finalList==null){
  72.                               finalList=currentNode;
  73.                               newHead=currentNode;
  74.                         }
  75.                         else{
  76.                               finalList.next=currentNode;
  77.                               finalList=finalList.next;
  78.                         }
  79.                   }
  80.             }
  81.             currentNode=currentNode.next;
  82.       }
  83.       if(finalList!=null)
  84.       finalList.next=null;
  85.      
  86.      
  87.      return newHead;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement