惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Vercel News
Vercel News
博客园_首页
Y
Y Combinator Blog
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
阮一峰的网络日志
阮一峰的网络日志
aimingoo的专栏
aimingoo的专栏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MyScale Blog
MyScale Blog
GbyAI
GbyAI
人人都是产品经理
人人都是产品经理
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
博客园 - Franky
Engineering at Meta
Engineering at Meta
量子位
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
N
Netflix TechBlog - Medium

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Remove Duplicates from Sorted Array
Jaspreet singh · 2026-06-15 · via DEV Community

Jaspreet singh

Problem Statement

Given a sorted integer array nums, remove the duplicates in-place such that each unique element appears only once.

Return the number of unique elements k.

The first k elements of the array should contain the unique elements in their original order.

Example

Input:

nums = [1,1,2]

Output:

2

Modified Array:

[1,2,_]


Brute Force Intuition (Interview Explanation)

One straightforward approach is to use a separate data structure like a HashSet to store unique elements.

As we traverse the array, we insert elements into the set and then copy them back into the original array.

Although simple, it violates the in-place requirement and uses extra memory.

Time Complexity

O(N)

Space Complexity

O(N)

Brute Force Java

class Solution {
    public int removeDuplicates(int[] nums) {

        HashSet<Integer> set = new HashSet<>();

        for (int num : nums) {
            set.add(num);
        }

        int index = 0;

        for (int num : set) {
            nums[index++] = num;
        }

        return set.size();
    }
}


Moving Towards Optimal

Since the array is already sorted, all duplicate values will appear together.

This means we do not need a HashSet.

We can maintain one pointer for the position of the last unique element and another pointer to explore the array.

Whenever we find a new unique value, we place it next to the previous unique value.

This gives an in-place solution with constant extra space.


Optimal Approach – Two Pointers

Algorithm

  1. Keep pointer i at the last unique element.
  2. Traverse the array using pointer j.
  3. If nums[j] is different from nums[i]:
    • Move i forward.
    • Place nums[j] at index i.
  4. At the end, unique elements occupy positions 0 to i.
  5. Return i + 1.

Why Two Pointers Work

Because the array is sorted:

1 1 1 2 2 3 4 4

All duplicates are adjacent.

So comparing the current element with the last unique element is enough to detect duplicates.


Optimal Java Solution

class Solution {
    public int removeDuplicates(int[] nums) {

        int i = 0;

        for (int j = 1; j < nums.length; j++) {

            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }
        }

        return i + 1;
    }
}


Dry Run

Input:

nums = [1,1,2,2,3,4,4]

Initial:

i = 0
j = 1

Step 1

nums[j] = 1
nums[i] = 1

Duplicate found

i = 0

Step 2

nums[j] = 2
nums[i] = 1

Unique element found

i = 1
nums[1] = 2

Array:

[1,2,2,2,3,4,4]

Step 3

nums[j] = 2
nums[i] = 2

Duplicate

Step 4

nums[j] = 3
nums[i] = 2

Unique

i = 2
nums[2] = 3

Array:

[1,2,3,2,3,4,4]

Step 5

nums[j] = 4
nums[i] = 3

Unique

i = 3
nums[3] = 4

Final Array:

[1,2,3,4,...]

Return:

i + 1 = 4


Pattern Recognition

This pattern is commonly used when:

  • Array is sorted
  • Duplicates need to be removed in-place
  • Stable ordering must be preserved
  • Constant extra space is required

Keywords that should trigger this pattern:

Sorted Array
In-place Modification
Remove Duplicates
Unique Elements

Think:

Two Pointers
Slow Pointer = Last Valid Position
Fast Pointer = Explorer


Interview One-Liner

Since the array is sorted, duplicates appear consecutively. Using a slow pointer to track the last unique element and a fast pointer to scan the array allows us to overwrite duplicates in-place, achieving O(N) time and O(1) space.