In the first approach, what about the remaining 2 positions in the array? You left them empty. The original array is of length 7 and new array with only unique elements has a length of 5, so what about the remaining 2 positions in the array? Java doesn't allow dynamic arrays so the length of the array is not changing .
In the first approach, every time the last element is getting added arr[j++]=arr[len-1], then if the last element is 5 and not 6 then 5 will again be added at the end and the output could be 1,2,4,5,5.
Hi Ranadheer, You missed that condition if (arr[i] != arr[i + 1]) { arr[j++] = arr[i]; } In this condition, Second last element is already compared with last element. So, in that case second last element won't be added. You can run the code and check the output.
@@ProgrammingTutorials1M I am not talking about second last. Consider 5 as the last element and there is no 6. Then last element 5 has to be added to our output and our output would be 1,2,4,5 and 5.
@@ranadheersannihith2362 no man, you got it wrong. arr = {1,2,4,4,5,5,5} 5 ! =5 is not satisfied till last element, so 5 will not be added to the array on iteration using for loop. {1,2,4} 5 only gets added when we add manually last element of array. arr = {1,2,4,5}
Hi All, I tried for this input -> int[] arr = {4,2,1,5,5,6,7,8,8,9}; Its removing the duplicate values but was not printing the last value i.e., 9 in this example. We need to use --> for (int i=0; i for (int i=0; i
Thank you so much!! for hashing and set the -1 must be removed, only keep it for the first code, which is great because I don't really understand why it needs to be -1
With this approach the problem is with line no: 74. This will throw ArrayIndexOutOfBoundsException when the size of the array is 0. And it adds extra burden to handle last element of Array. We can certainly improve this.
Good approaches. Is it possible to remove duplicates from unsorted array without using any collection. For example in O(1) or O(log n) space complexity
The code is amazing. Thank you so much. Subscribed 😊😊 Can you please tell how to find the non repeating elements in the array? i.e the elements which occur only once.
Can you use merge sort, and eject duplicates during merge routine? Or would all of those repeated shifts hurt the algorithm? I guess you can at least record the index of elements that are to be ejected during sorting.
But in this case the time complexity would be O(nlogn). There is a tradeoff between time and space here. Using extra space we can solve this problem in linear time.