Problem 26

Abstract / Summary

Given a sorted list of numbers remove duplicates in place and return the new length.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0026.cpp

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        auto i = unique(nums.begin(), nums.end());
        return distance(nums.begin(), i);
    }
};
7 lines | 180 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (10+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented implementation defines a Solution class with a single public method removeDuplicates. The method receives a reference to a vector<int> and returns an integer representing the count of unique elements after duplicate values have been eliminated. The core logic relies on the C++ Standard Library algorithm std::unique to perform the in-place removal, followed by std::distance to compute the resulting length.

Key Steps

The method consists of two distinct operations.

The first operation invokes std::unique on the range defined by nums.begin() and nums.end(). This algorithm scans the container, moving each distinct element forward to overwrite duplicates that appear consecutively. The call returns an iterator pointing just past the last element that should be considered part of the deduplicated sequence.

auto i = unique(nums.begin(), nums.end());

The second operation calculates the number of elements that remain in the logical view of the vector by measuring the distance from the beginning of the container to the iterator returned by unique. This distance corresponds to the new length of the array without duplicates.

return distance(nums.begin(), i);

Together, these two statements achieve the effect of collapsing consecutive duplicate entries while preserving the original order of the first occurrence of each value.

Edge Cases Handled

When the input vector is empty, nums.begin() equals nums.end(). The call to unique immediately returns the same iterator, and distance yields zero, correctly indicating that there are no elements to retain.

If the vector contains a single element, unique performs no modifications because there are no adjacent elements to compare. The returned iterator points to the element after the first, and distance returns one, reflecting the unchanged size.

For a vector where every element is identical, unique compresses the entire range to a single element at the front of the container. The iterator returned points to the second position, and distance computes a length of one, accurately representing the deduplicated result.

When the vector is already free of consecutive duplicates, unique leaves the container unchanged. The iterator returned coincides with nums.end(), and distance yields the original size, confirming that no elements were removed.

Performance Optimizations

The implementation leverages the highly tuned std::unique algorithm, which operates in linear time relative to the number of elements and performs all work in place. By avoiding auxiliary storage, the method minimizes memory overhead and benefits from cache locality inherent to contiguous vector storage.

The use of auto for the iterator type allows the compiler to deduce the most efficient iterator representation without incurring additional casting or type conversion costs.

Computing the result with std::distance on random-access iterators (as provided by vector) is a constant-time operation, ensuring that the final length calculation does not introduce any hidden traversal overhead.

Overall, the code achieves deduplication with a single pass over the data, reusing existing memory and relying on standard library primitives that are typically optimized for the target platform.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long line of numbered building blocks, but some of the blocks are exactly the same and are standing right next to each other. You want to make the line look tidier by removing the extra copies so that every number only appears once in a row.

The computer follows a very smart rule to help with this. The little word unique acts like a tiny cleanup robot that walks along the line of blocks. Every time this robot finds a block that is a copy of the one before it, it slides the different blocks forward to fill in the gaps. Once the robot reaches the very end of the line, all the blocks that are the same have been pushed to the back. The computer now knows exactly where the new, tidy line ends and where the leftover extra blocks begin.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 8.5 | μ = 8.25 | σ = 1.68

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
63 links | 45 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'How To Remove Duplicates From Sorted Array ( LeetCode 26 ) | FREE DSA Course in JAVA | Lecture 65'
TAP ACADEMY 19 mins
How To Remove Duplicates From Sorted Array ( LeetCode 26 ) | FREE DSA Course in JAVA | Lecture 65
YouTube video 'LeetCode in Java | Easy Question | Remove Duplicates from Sorted Array'
College Wallah 15 mins
LeetCode in Java | Easy Question | Remove Duplicates from Sorted Array
YouTube video 'Remove Duplicates from Sorted Array (Google, Amazon, Microsoft…) : Explanation ➕ Live Coding'
codestorywithMIK 10 mins
Remove Duplicates from Sorted Array (Google, Amazon, Microsoft…) : Explanation ➕ Live Coding
YouTube video 'Remove Duplicates From Sorted Array - Leetcode 26 - Arrays & Strings (Python)'
Greg Hogg 5 mins
Remove Duplicates From Sorted Array - Leetcode 26 - Arrays & Strings (Python)
YouTube video 'Remove Duplicates from Sorted Array | LeetCode 26 | Facebook Coding Interview Tutorial'
Terrible Whiteboard 12 mins
Remove Duplicates from Sorted Array | LeetCode 26 | Facebook Coding Interview Tutorial
YouTube video 'LeetCode 26: Remove Duplicates from Sorted Array - Interview Prep Ep 45'
Fisher Coder 15 mins
LeetCode 26: Remove Duplicates from Sorted Array - Interview Prep Ep 45
YouTube video 'REMOVE DUPLICATES FROM SORTED ARRAY (LeetCode)'
Engineering Digest 6 mins
REMOVE DUPLICATES FROM SORTED ARRAY (LeetCode)
YouTube video 'Remove Duplicates from Sorted Array | LeetCode 26 | Java'
Tech Tutor 10 mins
Remove Duplicates from Sorted Array | LeetCode 26 | Java
YouTube video '26. Remove Duplicates from Sorted Array | JavaScript | LeetCode Daily Challenge'
LeetCodeWithMonu 13 mins
26. Remove Duplicates from Sorted Array | JavaScript | LeetCode Daily Challenge
YouTube video 'Remove Duplicates from Sorted Array - Leetcode 26 - Coding Interview Questions'
nexTRIE 7 mins
Remove Duplicates from Sorted Array - Leetcode 26 - Coding Interview Questions
YouTube video 'LeetCode: 26. Remove Duplicates from Sorted Array (Visualized)'
Code With Zi 9 mins
LeetCode: 26. Remove Duplicates from Sorted Array (Visualized)
YouTube video 'Remove Duplicates from Sorted Array Python Solution - LeetCode #26'
Professor Oakes 5 mins
Remove Duplicates from Sorted Array Python Solution - LeetCode #26
YouTube video 'REMOVE DUPLICATES FROM SORTED ARRAY | LEETCODE 26 | PYTHON SOLUTION'
Cracking FAANG 10 mins
REMOVE DUPLICATES FROM SORTED ARRAY | LEETCODE 26 | PYTHON SOLUTION
YouTube video 'Remove Duplicates from Sorted Array | LeetCode Interview Solution Explained (Java + Whiteboard)'
Xavier Elon 7 mins
Remove Duplicates from Sorted Array | LeetCode Interview Solution Explained (Java + Whiteboard)
YouTube video 'LeetCode 26: Remove Duplicates from Sorted Array | C# Solution | Two Pointer Technique |'
Code Scribbler 8 mins
LeetCode 26: Remove Duplicates from Sorted Array | C# Solution | Two Pointer Technique |
YouTube video 'Can You Remove Duplicates? (LeetCode 80: Remove Duplicates from Sorted Array II)'
Code With Zi 9 mins
Can You Remove Duplicates? (LeetCode 80: Remove Duplicates from Sorted Array II)
YouTube video 'Leetcode 26: Remove Duplicates from Sorted Array in Telugu | Two Pointer Technique | srkcodes'
Srk Codes 9 mins
Leetcode 26: Remove Duplicates from Sorted Array in Telugu | Two Pointer Technique | srkcodes
YouTube video 'Leetcode |Top Interview 150| Easy |26. Remove Duplicates from Sorted Array | Time: O(N) | Javascript'
Software Interviews Prep 14 mins
Leetcode |Top Interview 150| Easy |26. Remove Duplicates from Sorted Array | Time: O(N) | Javascript
YouTube video 'Daily Leetcode #955: Nov 11, 2022 - 26. Remove Duplicates from Sorted Array'
Programming Live with Larry 5 mins
Daily Leetcode #955: Nov 11, 2022 - 26. Remove Duplicates from Sorted Array
YouTube video 'Leetcode Problem 26 EXPLAINED - Remove Duplicates from Sorted Array- Python Solution - Full Tutorial'
ClickJoy 5 mins
Leetcode Problem 26 EXPLAINED - Remove Duplicates from Sorted Array- Python Solution - Full Tutorial
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality