Efficiently Removing Duplicates from a Sorted Array

EngTeongCheah 66 views 15 slides May 31, 2024
Slide 1
Slide 1 of 15
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15

About This Presentation

The RemoveDuplicates method efficiently removes duplicates from a sorted array in-place using a two-pointer technique, ensuring a time complexity of O(n) and a space complexity of O(1). This approach maintains the order of elements and requires no additional data structures.


Slide Content

Remove Duplicates
from Sorted Array
EngTeongCheah

Questions
Given an integer arraynumssorted innon-
decreasing order, remove the duplicates in-place
such that each unique element appears
onlyonce. Therelative orderof the elements
should be kept thesame. Then returnthe number
of unique elements innums

Questions
Consider the number of unique elements ofnumsto
bek, to get accepted, you need to do the following
things:
-Change the arraynumssuch that the firstkelements
ofnumscontain the unique elements in the order they
were present innumsinitially. The remaining elements
ofnumsare not important as well as the size ofnums.
-Returnk.

Demo

Solution

Example Walkthrough
Let's walk through an example with
the input array nums= [1, 1, 2, 2, 3,
4, 4].
Initial state:
•nums= [1, 1, 2, 2, 3, 4, 4]
•i= 0
•j starts at 1

Example Walkthrough
First iteration (j = 1):
•nums[1] (1) is equal to nums[0] (1)
•No changes, move to the next
iteration.

Example Walkthrough
Second iteration (j = 2):
•nums[2] (2) is different from
nums[0] (1)
•Increment ito 1
•Assign nums[2] (2) to nums[1]
•nums= [1, 2, 2, 2, 3, 4, 4]

Example Walkthrough
Third iteration (j = 3):
•nums[3] (2) is equal to nums[1] (2)
•No changes, move to the next
iteration.

Example Walkthrough
Fourth iteration (j = 4):
•nums[4] (3) is different from
nums[1] (2)
•Increment ito 2
•Assign nums[4] (3) to nums[2]
•nums= [1, 2, 3, 2, 3, 4, 4]

Example Walkthrough
Fifth iteration (j = 5):
•nums[5] (4) is different from
nums[2] (3)
•Increment ito 3
•Assign nums[5] (4) to nums[3]
•nums= [1, 2, 3, 4, 3, 4, 4]

Example Walkthrough
Sixth iteration (j = 6):
•nums[6] (4) is equal to nums[3] (4)
•No changes, end of the loop.

Example Walkthrough
The final modified array is nums= [1,
2, 3, 4, 3, 4, 4] and the new length is
i+ 1 = 4.
The elements beyond the new length
(i.e., 3, 4, 4) are irrelevant as the
caller of the function is expected to
consider only the first i+ 1 elements
as valid.

CREDITS: This presentation template was created by Slidesgo,and includes
icons by Flaticon, and infographics & images by Freepik
Thanks!
Do you have any questions?
Please keep this slide for attribution

Resources
LeetcodeQ26 Remove Duplicates from Sorted Array