Mark As Completed Discussion

Good evening! Here's our prompt for today.

The Challenge: Unique Array Elements

You are given a sorted array of integers, named num. This array is special because it's sorted in non-decreasing order, meaning the numbers either stay the same or increase as you move through the array. However, there's a catch: the array might have duplicates, and your job is to make each number unique.

Example Scenarios

  1. First Scenario:

    • Original Array: num = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 8, 8]
    • Expected Outcome:
      • Length of Resultant Array: 8
      • Resultant Array: [1, 2, 3, 4, 5, 6, 8]

    Remove Duplicates from Sorted Array

  2. Second Scenario:

    • Original Array: num = [1, 2, 2, 3, 4, 4, 4, 5, 5]
    • Expected Outcome:
      • Length of Resultant Array: 5
      • Resultant Array: [1, 2, 3, 4, 5]

    Remove Duplicates from Sorted Array

Your Objective

Develop a program that takes this sorted array and eliminates any duplicate elements. The challenge is to do this while maintaining the original order of the elements.

Key Constraints

  • The input array, num, is sorted in a non-decreasing manner.
  • The length of num is always greater than 0.

Your task is to return two things: the length of the new array and the array itself, now with unique elements. This problem is a great way to understand array manipulation and the importance of maintaining order in data structures.

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's our guided, illustrated walk-through.

How do I use this guide?

Are you sure you're getting this? Click the correct answer from the options.

What would be the output for this array [1,2,2,3,6,6,9,10,10] after removing the duplicates? Click the option that best answers the question.

A. [1, 2, 4, 6, 10, 9]

B. [1, 2, 3, 6, 9, 10]

C. [1, 3, 4, 6, 10, 9]

D. [1, 2, 4, 6, 9, 10]

Click the option that best answers the question.

  • A
  • B
  • C
  • D

Disclaimer:

We have a very similar problem that we recently covered, called the Uniqueness of an Array. It is advisable not to mix it up with our current problem as the former one is removing duplicate elements from an unsorted array. In our case, we have a sorted array and therefore, allows us to use the two-pointers approach for an optimized solution. Let's look at the trivial brute force approach first before exploring the optimized solution.

Approaches:

Let's examine the two approaches and strategies and determine which is more efficient and optimized. Our first approach is brute force.

Brute Force Approach:

To identify and eliminate duplicates simultaneously, we may generate a new array that is the exact length of the original array and compare each element to its neighbor. In the case of a successful comparison, we would transfer one instance of the matching value from the original to the new array.

Solution Steps:

  • Return the array by checking if the array's length is 0 or 1.
  • Declare a variable temp to store the single instance of each element.
  • The input array will be scanned and copied a single instance of each element from arr to temp.
  • The variable p will be tracking the count of the single instance of each element.
  • We will copy each element's single instance from temp to arr.
  • And last, we will return the length of the array and the resultant arr by eliminating the duplicated element.

Brute Force Approach

Here's to reference code for a better understanding!

1var ob1;
2
3class BruteApproach{
4    removeDuplicates(arr,N) {
5        if (N === 0 || N === 1) {
6            return N;
7        }
8
9        var temp = new Array(N);		
10		var p = 0;
11        for (let i=0; i<N-1; i++){
12            if (arr[i] != arr[i+1]){
13                temp[p++] = arr[i];
14            }				
15        }
16        temp[p++] = arr[N-1];
17        for (let i=0; i<p; i++){
18            arr[i] = temp[i];
19        }
20		return p;
21    }
22}
23
24
25ob1 = new BruteApproach();
26nums=[2,3,4,4,5,6,6,6,7,8,8]
27a=ob1.removeDuplicates(nums, nums.length);
28var newarr = new Array(a);
29for (let z=0;z<a;z++){
30    newarr[z]=nums[z];
31}
32console.log(newarr);

Let's test your knowledge. Click the correct answer from the options.

What is the Space complexity of brute force?

Click the option that best answers the question.

  • O(n)
  • O(n!)
  • O(nlogn)
  • O(1)

Time Complexity:

The brute force approach has an O(n) time complexity, where n is the array's length. Moreover, the space complexity of the brute force approach is O(n) because a new array will be created, which will have the same length just like the original array.

Two Pointers Approach:

As we know that the given array is sorted in non-decreasing order, we can have two pointers, i and j, where i and j represent slow-runner and fast-runner, respectively. On the condition that nums[i] = num[j], j is incremented to skip duplicates. If we find that nums[i]!=nums[j] then we will conclude the duplicate run and its value must be copied to nums[i + 1]. we will then increase the i, and the process is repeated until j arrives at the end of the array.

Solution steps:

  • Initializing slow-runner and fast-runner variables i and j, respectively.
  • The input array will be scanned till j< length of nums.
  • We will identify a duplicate element by using this condition, nums[i]==nums[j]; if the above condition matches, then we will skip the duplicate element, and j will be incremented by 1. Likewise, we will identify the unique element using this condition, nums[i]!=nums[j], if the above condition matches, then i will be incremented by 1.
  • Lastly, we will copy nums[j] to nums[i] and increase j by 1.
  • We will repeat the above steps till j arrives at the end of the array, and the resultant output would be i+1 and the resultant array by eliminating the duplicated element.

Two Pointers Approach

Try this exercise. Click the correct answer from the options.

What is the Space complexity of Two pointer Approach?

Click the option that best answers the question.

  • O(n)
  • O(n!)
  • O(nlogn)
  • O(1)

Time Complexity:

The above approach has a time complexity of O(n), where n represents the number of array elements. We only need to traverse the complete array once to identify the unique element. Additionally, the space complexity of the preceding method is O(1), as no additional space is required to eliminate duplicates from the sorted array.

Now its time to try and play around with the final solution!

One Pager Cheat Sheet

  • We can develop a program to remove duplicate elements from a sorted array and return the length of the array, as well as the resultant array containing single instances of each element present.
  • By comparing elements at consecutive indices, the output of the array [1,2,2,3,6,6,9,10,10] after removing duplicates is [1, 2, 3, 6, 9, 10].
  • Bringing an optimized solution to the problem of removing duplicates from a sorted array using a two-pointers approach, after discussing the slower brute force approach.
  • Brute Force is the more efficient and optimized approach to the two discussed strategies.
  • The brute force approach to removing duplicates from a sorted array involves iterating through the array, copying one instance of each value from the original array to a temporary array, and then copying each single instance from the temporary array to the original array.
  • The total space complexity of the brute force approach is O(n), requiring additional memory equal to the size of the input array arr.
  • The brute force approach has an O(n) time and space complexity, where n is the array's length.
  • Using the two pointers approach, we can scan the given sorted array, identify duplicates and unique elements, and copy the unique elements to replace duplicates, in order to have a filtered array without duplicates.
  • This approach has a Space complexity of O(n) as it only utilizes two pointers, i and j.
  • The time complexity of this approach is O(n), where n is the number of elements in the array, and the space complexity is O(1) as no additional memory is required.

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Got more time? Let's keep going.

If you had any problems with this tutorial, check out the main forum thread here.