Problem Clearance: In this problem, you will be given an array of sorted integers. The array may or may not have repetitions. You have to remove the duplicates and find the number of distinct elements in that array. But there is a catch. You can not use any extra space to store the values. Also, the given array will have to be edited in such a way that it will contain only distinct elements. For example, if we have the following array ARR[] = 2 2 3 3 4 4 4 you will have to edit the array in such a way that the array has to contain ARR[] = 2 3 4 only. You have to return the number of distinct elements.
Tutorial: It is to count the number of distinct elements as the array is sorted. Just compare the next element with the current one. If you find a new element then just increase the count by 1. Finally, return the count.
Now for in-place duplication removal, keep traversing the array in a loop (as I did in while() loop) until a new element is found. Whenever you found a new element add it to the existing array in countth index. Take good care of traversing the array. For obvious reasons, it may get out of the index. In that case, try with the following inputs -
Input 1: []
Input 2: [1]
If you pass the given input above you can consider your code as accepted. Anyway, if you need more assistance please comment below.
I have added the code below for your reference.
Code:
int removeDuplicates(int* nums, int numsSize){
int cnt = 0;
for(int i=0; i<numsSize; ){
while(i<numsSize && nums[cnt] == nums[i]){
i++;
}
if(i >= numsSize) break;
cnt++;
nums[cnt] = nums[i++];
}
printf("%d\n", cnt);
return (numsSize == 0? numsSize : cnt + 1);
}
If you need any more clarifications on this problem please comment.
=>Leave a comment for any kinds of Hugs and/or Bugs. Thank you.
=>Leave a comment for any kinds of Hugs and/or Bugs. Thank you.
No comments:
Post a Comment