Advertisement
satishfrontenddev5

Untitled

Feb 22nd, 2024
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Problem Description
  2. Given a sorted array, remove all duplicates such that each element occurs at most once in the array. Return the length of the modified array.
  3.  
  4. Note : The input array should be modified in-place i.e. no extra memory should be allocated to any other array and the question should be solved by using O(1) memory.
  5.  
  6. Input format
  7. There are two lines of input.
  8.  
  9. The first line consists of an integer N, which denotes the size of the input array
  10.  
  11. The second line consists of N space separated integers, which acts as our input array.
  12.  
  13. Output format
  14. Prints the size of the modified array which consists of no duplicates.
  15.  
  16. Function Definition
  17. Complete the function removeDuplicates.
  18.  
  19. removeDuplicates has the following parameters :
  20.  
  21. nums : An array of numbers in the sorted order
  22.  
  23. removeDuplicates returns :
  24.  
  25. int : An integer denoting the size of the modified array.
  26.  
  27. Constraints
  28. 0 <= N <= 10^6
  29.  
  30. 1 <= A[i] <= 10^9
  31.  
  32. where A[i] denotes the ith element of the input array.
  33.  
  34. Sample Input 1
  35. 7
  36.  
  37. 2 4 4 4 6 8 8
  38.  
  39. Sample Output 1
  40. 4
  41.  
  42. Explanation 1
  43. The array can be modified to [2,4,6,8] after removing all duplicates ensuring that all elements occur once. The length of this array is 4 , hence 4 is the output.
  44.  
  45. Sample Input 2
  46. 4
  47.  
  48. 2 2 3 11
  49.  
  50. Sample Output 2
  51. 3
  52.  
  53. Explanation 2
  54. The array can be modified to [2,3,11] after removing all duplicates ensuring that all elements occur once. The length of this array is 3 , hence 3 is the output.
  55.  
  56. function removeDuplicatesFromSortedArray(arr) {
  57.   const n= arr.length;
  58.   if(n<=1)
  59.   return n;
  60.   let i=0;
  61.   let j=0;
  62.   while(j<n){
  63.     if(i==j){
  64.       j++;
  65.     }
  66.     else{
  67.       // i!=j now we have 2 cases:
  68.       if(arr[j]!=arr[i]){
  69.           i++;
  70.           arr[i]=arr[j];
  71.           j++;
  72.       }
  73.       else{
  74.         j++;
  75.       }
  76.     }
  77.     // console.log(i);
  78.   }
  79.   return (i+1);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement