~/coding-interview/leetcode-solution-remove-duplicates-from-sorted-array.md

Remove Duplicates from Sorted Array - Leet Code Solution

// TL;DR

Since the array is sorted, duplicates are adjacent. Use a slow pointer for the write position — advance it only when the fast pointer finds a new value. O(n) time.

Remove Duplicates from Sorted Array - Leet Code Solution

Problem Statement

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Note:

  1. We have to return the new length
  2. And, modify the array also

Constraint
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Examples

# Example 1
   Given nums = [1,1,2],
   Output = 2

# Example 2
   Given nums = [0,0,1,1,1,2,2,3,3,4],
   Output = 5

Solution (Using an extra variable)

First think out loud about the problem.

  • Its a sorted array,
  • And, which means a number which is repeating would occur later after another number.

Code

Lets look at the code

public int removeDuplicates(int[] nums) {
   if (nums == null || nums.length == 0) {
      return 0;
   }
   int num = nums[0];
   int j=1;
   
   for (int i=1; i<nums.length; i++) {
      if (num != nums[i]) {
         num = nums[i];
         
         nums[j] = nums[i];
         j ++;
      }
   }
   
   return j;
   }

Steps

  • We can begin with first index value, save it in a variable.
  • We can keep another variable for storing our index j, which will point to index upto which our array is unique.
  • This index variable will increment after finding a unique value only.
  • And, we need to copy that unique value to our array as well.

Results

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 41.1 MB, less than 87.80% of Java online submissions for Remove Duplicates from Sorted Array.

Code without extra variable

public int removeDuplicates2(int[] nums) {
   if (nums == null || nums.length == 0) {
      return 0;
   }
   int j=1;
   for (int i=1; i<nums.length; i++) {
      if (nums[j-1]!= nums[i]) {
         nums[j]= nums[i];
         
         j ++;
      }
   }
   
   return j;
   }

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…