remove duplicates

2 Ways to Remove Duplicates from Sorted Array – O(n) time

Given an input array of integers, your goal is to remove duplicates present from an sorted array in O(n) time by method 1: using extra space i.e., O(n) space and by method 2: using constant space i.e., O(1) space.

Method 1: Algorithm – Using Extra Space

Below is the algorithm to remove duplicates from sorted array using extra space (temp[] array)

Solution 1: RemoveDuplicatesSortedArrayExtraSpace.iava

Output

Time Complexity – O(n) time (Single Traversal)

Space Complexity – O(n) space (Since an array temp[] extra space is created/utilized to store unique elements)

Method 2: Algorithm – Without Extra Space

Below is the algorithm to remove duplicates from sorted array without any extra space.

In this approach maintain the separate index for the same array i.e., inArray[] instead of creating temp[] array (different array) to store unique elements.

Solution 2: RemoveDuplicatesSortedArrayContantSpace.java

Output

Time Complexity – O(n) (Single Traversal)

Space Complexity – O(1) (Since maintaining separate index for the same array i.e., inArray[] instead of creating temp[] array i.e., different array to store unique elements)

Recommended Posts

Reference

Leave a Reply

avatar
  Subscribe  
Notify of