DEV Community

Cover image for Removal of Duplicate Sorted Array with Dart.
Kushimo Bashir
Kushimo Bashir

Posted on

Removal of Duplicate Sorted Array with Dart.

To start with I'm Bashir by name. A flutter developer who developed interest in using Dart as an Approach for Data structure and Algorithm.
I stumbled upon an easy task on leetcode and i decided to document the solution in an article. I hope is sounds cool right? yea😁.
The question goes thus;

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

link to the question: https://leetcode.com/problems/remove-duplicates-from-sorted-array/

Solution:
Step 1: Don't forget in the first paragraph of the question, we are been told to remove the duplicate of (nums) sorted array.
One of the easiest way of doing that is to convert the array to a Set. I hope you get that? GOOD!👍

step 2: Emphasis on second paragraph it was stated that the sorted list must be place in first part of the sorted array nums.
Now, the best thing to do firstly is to convert the Set from step one to a list.

Step 3: Returning the length of the new list.

Here is the solution below using Dart

class Solution {
  int removeDuplicates(List<int> nums) {
  var toSet = nums.toSet();
  var toList = toSet.toList();
   int toListLength = toList.length; 
     for(int i=0; i<toList.length; i++){
         nums[i]=toList[i];
     } 
      return toListLength; 
  }
}
Enter fullscreen mode Exit fullscreen mode

I hope this is pretty easier Thank you all for reading!

Top comments (0)