Master Remove Duplicates from Sorted Array – Python Tricks You Need to Know

Share with friends
⏱️ 𝑹𝒆𝒂𝒅𝒊𝒏𝒈 𝑻𝒊𝒎𝒆: 3 𝘮𝘪𝘯𝘶𝘵𝘦𝘴 ⚡️
Save Story for Later (0)
Please login to bookmark Close

🧠 Imagine This: Sorting Socks with Your Eyes Closed

Picture this: You’ve just done laundry, and you’re sorting socks. You notice that your sock drawer is already sorted by color. White, white, white… blue, blue… red, red.
Now, your task is to remove the duplicates so that there’s only one sock of each color on display.

Sounds simple? That’s exactly what we’re going to do with a sorted array!


🧱 What’s the Problem Statement?

Let’s understand what LeetCode and coding interviews mean by:

🧩 “Remove Duplicates from Sorted Array”

Given:
A sorted list of integers (in non-decreasing order).

Task:
Remove the duplicates in-place. Ensure each unique element appears only once. Return the new length of the modified array.

You must do this without using extra space (i.e., constant space only).


Why Sorted Arrays Help Us Here?

Imagine you’re reading a line of words sorted alphabetically. If one word is the same as the one before, it’s a duplicate, right?

Since the array is already sorted, all duplicates will sit next to each other. This makes it super easy to compare one element with the one before it and decide whether it’s a duplicate.


💡 Real-Life Analogy: Clearing Your Contact List

Think of your phone’s contact list. You might have multiple entries for “Mom” or “Alex”. If the list is sorted, you can scroll through and remove the extras easily because they’re all grouped together.

Same goes for our array—our job is to scroll through, compare, and keep only the first unique one.


🛠️ Solution Walkthrough: Step-by-Step

We’ll solve this using the two-pointer technique, which is like having two fingers walking through the array:

✅ Step-by-Step Logic

  1. One pointer (i) keeps track of the last unique element.
  2. The other pointer (j) explores the rest of the array.
  3. If nums[j] != nums[i], we move i forward and copy nums[j] to nums[i].

Here’s how it looks:

Input: nums = [0,0,1,1,1,2,2,3,3,4]

Algorithm:

  • Start with i = 0
  • For j from 1 to len(nums)-1:
    • If nums[j] != nums[i]:
      • Increment i
      • nums[i] = nums[j]

Output: New length = 5
Modified array = [0,1,2,3,4,…]


🔍 Why This Works Efficiently

  • Time Complexity: O(n) — we go through the array once.
  • Space Complexity: O(1) — no extra array needed.

🔄 Variants You Might See

  • What if the array isn’t sorted?
    You’ll need to sort it first (O(n log n)) and then apply this logic.
  • What if we want to return the new array instead of the length?
    Just slice: nums[:k], where k is the new length.

⚡ Pro Tips for Mastery

Tip 1: Use the two-pointer technique for any in-place array problems. It’s a go-to trick! 👣
Tip 2: Don’t worry about what comes after the new length. Interviewers don’t care — just modify the first k elements. 🚀
Tip 3: Avoid extra memory unless asked — space-efficient solutions score more points. 📉
Tip 4: Practice this with strings and characters too — same principle applies! 🔤
Tip 5: Naming your pointers meaningfully (unique_index, scanner) helps readability. 🧠


❌ Common Mistakes to Avoid

🚫 Using another array to store uniques – not allowed in this problem!
🚫 Forgetting the array is sorted – don’t waste time checking all elements.
🚫 Not updating the array in-place – don’t return a new one unless asked.


🧠 Expert Insight: Why This Shows Up in Interviews

Interviewers love this question because:

  • It tests array manipulation.
  • It checks your understanding of in-place operations.
  • It reveals if you know space/time trade-offs.

🔥 Pro Insight: This problem lays the foundation. It helps solve more complex array problems like “Move Zeroes”, “Merge Sorted Arrays”, and “Remove Element”.

Try it Yourself


🏁 Final Thoughts

You just crushed one of the most frequently asked array problems. 🎉
Give yourself a high five — or better, run through it again from memory. You’ll be amazed at how much you remember.

Keep Practicing. Keep Crushing It. 💪
See you in the next post, where we break down — the next logical problem!

Article Contributors

  • Alfred Algo
    (Author)
    Chief Algorithms Scientist, QABash

    Alfred Algo is a renowned expert in data structures and algorithms, celebrated for his ability to simplify complex concepts. With a background in computer science from a prestigious university, Alfred has spent over a decade teaching and mentoring aspiring programmers. He is the author at the popular blog "The Testing Times," where he shares tips, tutorials, and insights into mastering DSA.

  • Ajitesh Mohanta
    (Reviewer)
    Automation Engineer, Grab

    Experienced SDET with a strong QA background, specializing in API, manual, and automation testing. Skilled in SQL, Python, and Selenium for both backend and frontend automation. Committed to delivering high-quality software.

Subscribe to QABash Weekly 💥

Dominate – Stay Ahead of 99% Testers!

Leave a Reply

Scroll to Top
×