LeetCode 27: Remove Element is an Easy array / string problem. This Python walkthrough develops a write pointer solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Array / String |
| Reusable pattern | write pointer |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, scan once and copy only values that should remain into the next output position. The prefix before the write pointer is the compacted result. The invariant worth writing beside the code is: The prefix before write contains exactly the retained values seen so far.
Step-by-step algorithm
- Identify the input state consumed by
removeElement(nums, val)and initialize the data required by the write pointer pattern. - Scan once and copy only values that should remain into the next output position. The prefix before the write pointer is the compacted result.
- After each update, verify the page’s central invariant: The prefix before write contains exactly the retained values seen so far.
- Finish only after the boundary behavior is covered: All values may be removed, or none may match the target.
Python solution
class Solution:
def removeElement(self, nums, val):
write = 0
for value in nums:
if value != val:
nums[write] = value
write += 1
return writeReading the implementation
The main entry point is removeElement(nums, val). The named working state includes write; those variables make the write pointer state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, scan once and copy only values that should remain into the next output position. The prefix before the write pointer is the compacted result.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Scan once and copy only values that should remain into the next output position. The prefix before the write pointer is the compacted result. Each update records the current item without invalidating earlier decisions; consequently, the prefix before write contains exactly the retained values seen so far.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
nums = [3,2,2,3]; k=Solution().removeElement(nums,3); assert nums[:k] == [2,2]Common mistakes and edge cases
- Problem-specific boundary: All values may be removed, or none may match the target.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that the prefix before write contains exactly the retained values seen so far.
Interview review checklist
- Explain why write pointer matches the structure of this input.
- State the invariant in one sentence before tracing code: The prefix before write contains exactly the retained values seen so far.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: All values may be removed, or none may match the target.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 88. Merge Sorted Array · Next: 26. Remove Duplicates from Sorted Array