Problem 27

Abstract / Summary

Given a list and a value remove all instances of that value in place and return the new length of the list.

Note

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

C++ 0027.cpp

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        for (auto i = 0; i < nums.size(); i++)
            if (nums[i] == val)
                nums[i] = 999;

        sort(nums.begin(), nums.end());

        while (!nums.empty() && nums.back() == 999)
            nums.pop_back();

        return nums.size();
    }
};
15 lines | 363 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 62% (8+ 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 provides a method to remove all occurrences of a specified value from a mutable integer array while returning the new length of the array. The algorithm proceeds in three distinct phases: marking elements that match the target value, reordering the array so that marked entries are positioned at the end, and finally discarding those trailing markers. All operations are performed in-place, preserving the original container without allocating auxiliary storage.

Step 1: Marking Elements for Removal

The first phase iterates over the entire vector and replaces any element equal to the target value with a sentinel constant (999). This sentinel is chosen because it is unlikely to appear in typical input data, allowing the later stages to identify and isolate the elements slated for removal.

for (auto i = 0; i < nums.size(); i++)
    if (nums[i] == val)
        nums[i] = 999;

By directly overwriting matching entries, the algorithm avoids the need for a secondary buffer or additional bookkeeping structures.

Step 2: Sorting to Group Marked Elements

After marking, the vector is sorted using the standard library sort. Because the sentinel value is larger than most ordinary inputs, the sort operation moves all sentinel entries to the tail of the container, clustering them together.

sort(nums.begin(), nums.end());

This step leverages the highly optimized introsort implementation provided by the standard library, ensuring that the reordering is performed efficiently while still operating in-place.

Step 3: Trimming Marked Elements

With all sentinel values now contiguous at the end of the vector, a simple loop removes them by repeatedly popping the last element while it equals the sentinel. The loop terminates as soon as a non-sentinel element is encountered or the vector becomes empty.

while (!nums.empty() && nums.back() == 999)
    nums.pop_back();

The use of pop_back eliminates elements without shifting the remaining contents, preserving the order of the unmarked elements that remain.

Edge Cases Handled

When the input vector is empty, the initial loop executes zero iterations, the sort operates on an empty range, and the trimming loop exits immediately, resulting in a returned size of zero. If every element matches the target value, each entry is replaced by the sentinel, the sort places all sentinels at the end, and the trimming loop removes the entire vector, again yielding a size of zero. Conversely, if no element equals the target value, the marking loop makes no modifications, the sort leaves the vector unchanged, and the trimming loop finds no sentinel at the back, so the original size is returned unchanged. The algorithm also gracefully handles cases where the sentinel value (999) might already be present in the input; such occurrences are indistinguishable from marked entries after sorting, effectively treating them as removable, which aligns with the intended semantics of removing the target value.

Performance Optimizations

The method achieves in-place transformation by reusing the original storage for both marking and final result, eliminating the overhead of auxiliary arrays. The sentinel marking avoids conditional branching during the trimming phase, allowing the subsequent sort to handle all elements uniformly. Leveraging the standard library’s sort provides a well-tuned, cache-friendly ordering routine that benefits from branch prediction and vectorized moves. The final removal uses pop_back, which operates in constant time and does not trigger element relocation, ensuring that the cost of discarding marked entries scales linearly with the number of removals rather than with the total size of the vector. Together, these choices produce a solution that balances simplicity with efficient use of memory and CPU resources.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks lined up on the floor. Some of these blocks have a sticker on them that you do not like, so you want to get rid of them.

First, the code walks down the line of blocks one by one. When it finds a block that matches the one you want to remove, it paints that block with a special number, nine hundred ninety nine, to mark it as unwanted.

Next, the code takes all the blocks and rearranges them so that all the ordinary blocks are at the front and all the blocks marked with nine hundred ninety nine are pushed to the very end of the line.

Finally, the code looks at the very end of the line to see if there are any marked blocks sitting there. If it finds one, it picks it up and puts it away, repeating this until all those marked blocks are gone and only the ones you want to keep are left.

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 = 3.5 | μ = 3.64 | σ = 1.34

Complexity Analysis

Time: loglinear
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 Rust C# JS Java Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 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
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
YuriSpiridonov Python
zfang399 C++
60 links | 42 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 27: Remove Element'
Algo Engine 4 mins
LeetCode 27: Remove Element
YouTube video 'Remove Element - Leetcode 27 - 2 Pointers (Python)'
Greg Hogg 5 mins
Remove Element - Leetcode 27 - 2 Pointers (Python)
YouTube video 'Remove Element |  LeetCode Question 27'
Jenny's Lectures CS IT 19 mins
Remove Element | LeetCode Question 27
YouTube video 'Leetcode | 27. Remove Element | Easy | Java Solution'
Developer Docs 5 mins
Leetcode | 27. Remove Element | Easy | Java Solution
YouTube video 'How to Solve "27 Remove Element" on LeetCode? - Javascript'
Becoming A Better Dev (with David) 6 mins
How to Solve "27 Remove Element" on LeetCode? - Javascript
YouTube video 'LeetCode: 27. Remove Element (Visualized)'
Code With Zi 10 mins
LeetCode: 27. Remove Element (Visualized)
YouTube video 'Leetcode | Top Interview 150 | Easy | 27. Remove Element | Time: O(N) | Javascript'
Software Interviews Prep 10 mins
Leetcode | Top Interview 150 | Easy | 27. Remove Element | Time: O(N) | Javascript
YouTube video 'Remove Element Python Solution - LeetCode #27'
Professor Oakes 4 mins
Remove Element Python Solution - LeetCode #27
YouTube video 'Leetcode 27: Remove Element in Telugu  | Two Pointers | Python DSA | srkcodes'
Srk Codes 10 mins
Leetcode 27: Remove Element in Telugu | Two Pointers | Python DSA | srkcodes
YouTube video 'LeetCode 27: Remove Element | C# Solution | Two Pointer Technique |'
Code Scribbler 8 mins
LeetCode 27: Remove Element | C# Solution | Two Pointer Technique |
YouTube video '27. Remove Element (Leetcode Easy)'
Programming Live with Larry 8 mins
27. Remove Element (Leetcode Easy)
YouTube video 'Remove Element | Leetcode 27 | Approach + Code with explanation.'
Pirai's Academy 19 mins
Remove Element | Leetcode 27 | Approach + Code with explanation.
YouTube video '27. Remove Element - LeetCode 101'
Software Interviews Prep 6 mins
27. Remove Element - LeetCode 101
YouTube video 'Day 14: LeetCode Problem 27.  Remove Element - Swift'
iOSxBank 8 mins
Day 14: LeetCode Problem 27. Remove Element - Swift
YouTube video '27. Remove Element |  Two Pointers | O(N) | Top Interview 150 | LEETCODE | Easy'
Software Interviews Prep 7 mins
27. Remove Element | Two Pointers | O(N) | Top Interview 150 | LEETCODE | Easy
YouTube video '27. Remove Element | Approach 1: Two Pointers | O(N) | Leetcode | Easy | Javascript'
Software Interviews Prep 6 mins
27. Remove Element | Approach 1: Two Pointers | O(N) | Leetcode | Easy | Javascript
YouTube video 'Remove Element || problem 27 || leetCode #coding #java #javatutorial #learning'
Study Placement 4 mins
Remove Element || problem 27 || leetCode #coding #java #javatutorial #learning
YouTube video 'Leetcode | Easy |  27. Remove Element. | Two Pointer | Time complexity: O(n) | Javascript'
Software Interviews Prep 7 mins
Leetcode | Easy | 27. Remove Element. | Two Pointer | Time complexity: O(n) | Javascript
YouTube video 'LeetCode 27 | Remove Element | 2 Pointers | Java'
Sleepy Cracker 4 mins
LeetCode 27 | Remove Element | 2 Pointers | Java
YouTube video 'Amazon Software Engineer Interview Preparation - Part 23 LC  27 Remove Element'
Ghumman Tech 5 mins
Amazon Software Engineer Interview Preparation - Part 23 LC 27 Remove Element
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 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