⬅ Previous Topic
Check if Array is SortedNext Topic ⮕
Left Rotate an Array by One Place⬅ Previous Topic
Check if Array is SortedNext Topic ⮕
Left Rotate an Array by One PlaceTopic Contents
Given a sorted array of integers, your task is to remove the duplicate elements in-place such that each element appears only once. The relative order of the elements should be maintained.
arr
.i
to track unique elements and j
to iterate through the array.i = 0
and j = 1
.arr[j] != arr[i]
, increment i
and update arr[i] = arr[j]
.j
reaches the end of the array.i + 1
elements are the array with duplicates removed.def remove_duplicates(arr):
if not arr:
return 0
i = 0
for j in range(1, len(arr)):
if arr[j] != arr[i]:
i += 1
arr[i] = arr[j]
return i + 1
# Sample Input
arr = [1, 1, 2, 2, 3, 4, 4]
k = remove_duplicates(arr)
print("After removing duplicates:", arr[:k])
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Even if all elements are duplicates, the algorithm still iterates through the entire array once. |
Average Case | O(n) | Regardless of how many duplicates exist, each element is visited once using the two-pointer approach. |
Average Case | O(n) | In the worst case where all elements are unique, the algorithm still makes a single pass through the array. |
O(1)
Explanation: The algorithm operates in-place and only uses two pointers to modify the array without allocating extra space.
Let's remove duplicates from the sorted array using the two-pointer technique.
Initialize pointer i = 0
to track the last unique element. Start loop from j = 1
.
Compare arr[1] = 1
with arr[0] = 1
.
Duplicate found. Do nothing.
Compare arr[2] = 2
with arr[0] = 1
.
Values are different. Increment i
to 1 and set arr[1] = 2
.
Compare arr[3] = 2
with arr[1] = 2
.
Duplicate found. Do nothing.
Compare arr[4] = 3
with arr[1] = 2
.
Values are different. Increment i
to 2 and set arr[2] = 3
.
Compare arr[5] = 4
with arr[2] = 3
.
Values are different. Increment i
to 3 and set arr[3] = 4
.
Compare arr[6] = 4
with arr[3] = 4
.
Duplicate found. Do nothing.
Array without duplicates (first i + 1 which is 4
elements): [1,2,3,4]
⬅ Previous Topic
Check if Array is SortedNext Topic ⮕
Left Rotate an Array by One PlaceYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.