Remove Duplicates from Sorted Array - LeetCode Java Solution

I'm a tech enthusiast who loves building backend systems that just work — clean, scalable, and efficient. I've worked with microservices, Spring Boot, Azure, and APIs, and I enjoy digging into root causes and making systems better. Whether it's writing clean code, reviewing it, or managing deployments with DevOps tools, I'm always up for the challenge. I like working in collaborative environments where I can learn, share, and grow alongside smart people.
👋 Introduction
Welcome to my LeetCode Solutions in Java series! In each post, I’ll break down one LeetCode problem with a clear explanation, Java code, and a complexity analysis.
Today we will solve the problem: Remove Duplicates from Sorted Array.
🔍 Problem Statement
Given: A sorted array nums in non-decreasing order.
Task: Remove duplicates from sorted array, so that unique element appears only once.
Return: The new length k, where first k elements in nums are unique.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
💡 Approach
Here, we will make use of two pointers - one to keep track of the current element and another one to keep the reference.
Initialise
reference = 0;Loop
currentfrom1toendIf
nums[current] != nums[reference]:Increment
referenceSet
nums[reference] = nums[current](move unique forward)
Return
reference + 1as the new length of the array.
🧠 Java Code
class Solution {
public int removeDuplicates(int[] nums) {
int reference = 0;
for (int current = 1; current < nums.length; current++) {
if (nums[current] != nums[reference]) {
reference++;
nums[reference] = nums[current];
}
}
return reference + 1;
}
}
⏱️ Time Complexity
✅ Best & Worst Case: O(n)
We iterate through the array once →
O(n)There are no other operations, hence total time complexity →
O(n)
🧮 Space Complexity
✅ Best & Worst Case: O(1)
We are introducing only two variables despite of the size of input array.
Hence, space complexity is
O(1)
🧩 Related Topics
Array
Two Pointers
Stay tuned for the next problem in this series!




