Remove Elements
Given an array representing a linked list and a target value, remove all occurrences of the target from the list and return the resulting array. This is equivalent to deleting all nodes in a linked list that contain a specific value.
For example, removing 6 from [1, 2, 6, 3, 4, 5, 6] produces [1, 2, 3, 4, 5]. Removing 7 from [7, 7, 7, 7] produces []. If no elements match the target, the array is unchanged: removing 4 from [1, 2, 3] produces [1, 2, 3]. An empty array returns [].
Removing elements from a linked list is a fundamental operation. In a real linked list, removal involves updating the previous node's next pointer to skip the removed node. If the removed node is the head, the head pointer must be updated. If the removed node is in the middle, the previous node's next pointer is redirected to the removed node's next.
In the array version, you filter out matching elements while preserving the order of remaining elements. This is simpler than the linked list version because you do not need to manage pointers — you just build a new array with the non-matching elements.
Edge cases include an empty array (return []), an array where all elements match (return []), an array where no elements match (return the original), and the target matching only the first or last element.
Example Input & Output
All removed
No match
All duplicates removed
Empty array
Remove all 6s
Algorithm Flow

Solution Approach
Filter the array to keep only elements that do not match the target value.
Create an empty result array. Iterate through the input, pushing elements that are not equal to the target. This preserves the original order of remaining elements.
For the linked list version: create a dummy head node to simplify the edge case of removing the actual head. Iterate with a pointer, updating the next pointer to skip matching nodes.
Time complexity is O(n), space complexity is O(n) for the result array.
Best Answers
class Solution {
public int[] solution(int[] nums, int val) {
int c=0;for(int n:nums){if(n!=val)c++;}int[] r=new int[c];int i=0;for(int n:nums){if(n!=val)r[i++]=n;}return r;
}
}Related Linked List Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
