Skip to content

Remove Duplicates

LeWiz24 edited this page Aug 22, 2025 · 12 revisions

Unit 3 Session 2 (Click for link to problem statements)

TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Lists, Two-pointer technique

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the input to the function?

    • A: The input is a sorted list nums containing elements that may have duplicates.
  • Q: What is the expected output of the function?

    • A: The function should return the length of the list after removing duplicates, with the duplicates removed in-place.
  • Q: Should the original list be modified?

    • A: Yes, the function should modify the original list in-place to remove duplicates.
  • Q: Can additional lists or data structures be used?

    • A: No, the problem requires that no additional list or data structures be used.
  • Q: What if the list is empty?

    • A: If the list is empty, the function should return 0.
  • The function remove_dupes() should take a sorted list and remove duplicates in place, modifying the original list. Return the length of the modified list, where each element appears only once.

HAPPY CASE
Input: ["honey", "haycorns", "thistle", "thistle", "extract of malt"]
Expected Output: 4
Modified List: ["honey", "haycorns", "thistle", "extract of malt", ...]

EDGE CASE
Input: ["honey", "haycorns", "extract of malt", "thistle"]
Expected Output: 4
Modified List: ["honey", "haycorns", "extract of malt", "thistle"]

Input: []
Expected Output: 0
Modified List: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use two pointers to track the position of unique elements in the sorted list. One pointer will iterate through the list to find unique elements, while the other will maintain the position for placing unique elements.

1. If the input list `nums` is empty, return 0.
2. Initialize a pointer `i` to 0 to track the last unique element's position.
3. Loop through the list starting from index 1:
   a. If the current element is different from the last unique element (nums[i]), increment `i` and update nums[i] with the current element.
4. Return `i + 1` to get the length of the modified list

⚠️ Common Mistakes

  • Not handling the empty list case.
  • Incorrectly updating the index for unique elements.

I-mplement

Implement the code to solve the algorithm.

def remove_duplicates(nums):
    if not nums:
        return []

    write = 1  # next position to write a new unique value
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1

    # remove the leftover tail (the old duplicates)
    del nums[write:]
    return nums
Clone this wiki locally