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();
}
};
Difficulty
and has an acceptance rate of about 62% (8+ million submissions).
Typical patterns to solve this problem:
- Array
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 26: Remove Duplicates from Sorted Array
- problem 203: Remove Linked List Elements
- problem 283: Move Zeroes
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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