Skip to main content

Command Palette

Search for a command to run...

[LeetCode] Top Interview 150 Problems Solving # 26 Remove Duplicates from Sorted Array

Updated
2 min read
R

South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?

Understanding the Problem

A given list nums has numbers from -100 to 100 in an arranged order. The task is to change nums in place by finding duplicate numbers and removing them. nums should stay with unique numbers only. It is not important to return any value from the function as this problem only deals with nums.

Approach

Should I go with remove() method or replace()? remove() will cause an error in the loop so I decided to replace the duplicate numbers into something that could be marked as duplicate and removed later.

Solution

  1. I wanted to keep the unique numbers somewhere as temp, to use it for checking other numbers whether they are duplicate or not.

  2. I would go by for loop while checking unique numbers. If the number nums[i] is not unique and has been duplicate, I changed it with -1000.

  3. I sorted the number to have -1000 numbers to the starting of the index.

  4. Then I redeclared nums with the sliced nums, which sliced all -1000 numbers.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        temp = []
        for i in range(len(nums)):
            if nums[i] not in temp:
                temp.append(nums[i])
            else:
                nums[i] = -1000

        nums.sort()
        count = nums.count(-1000)
        nums[:] = nums[count:]
        return

Reflection

Changing the number in place is a little bit tricky, and the methods may be not working the way I think it should. I guess it is only the matter of practice.

Another thing that I noticed on LeetCode is, that there is a lack of explanation so in some problems I myself need to find a way to break through the barriers towards the solution, interpreting what the actual instruction is and what to return. This problem too. It tells me to return the k which is the length of the unique numbers but it was nothing about the k. Well, I guess I will figure solution out myself and just go with it.

More from this blog

R

Ramieeee's IT blog

36 posts

Algorithms, IT news, my thoughts note