DEV Community

Vinicius Basilio
Vinicius Basilio

Posted on

LeetCode journal: Remove Duplicates from array

When I started these posts, I was just having fun as a hobbyist programmer, but recently I started to CS in college, so my posts will become more technical.

For this serie, I wanna post my LeetCode solutions; everytime when I achive 100% in runtime analysis or at least 80% in memory efficiency, I will share my code here.

Posts will follow leetcode model:

Image description

Intuition

Another simple two pointers trick. Let a pointer for the first item of array (call it index). Then use another pointer to search, keep waiting a different item to appear. At this time, just increase by one our index pointer and copy the value pointed by the other one.

Approach

We will build a "for loop", is easy to loop through array with this loop. We'll need to mutable vars, one to hold our "lazy" pointer, the one that memorized the next index, and another for search, this var will be updated just when the index value became different from the search pointer.

Complexity

Time complexity:
o(n)

Space complexity:
o(1)

Code

impl Solution {
    pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
      let mut lastNonDup = nums[0];
      let mut new_size= 1;

        for index in 0..nums.len() {
            if nums[index] != lastNonDup {
                nums[new_size] = nums[index];
                new_size += 1;
                lastNonDup = nums[index];
            }
        }
        new_size as i32  
    }
}

My leetcode: https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/6745076/solution-in-rust-for-remove-duplicates-f-njsb/

Top comments (0)