Code Logo

Remove Elements

Published at25 Jul 2026
Operations Easy 0 views
Like0

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

Example 1
Input
[7,7,7,7],7
Output
[]
Explanation

All removed

Example 2
Input
[1,2,3],4
Output
[1,2,3]
Explanation

No match

Example 3
Input
[2,2],2
Output
[]
Explanation

All duplicates removed

Example 4
Input
[],1
Output
[]
Explanation

Empty array

Example 5
Input
[1,2,6,3,4,5,6],6
Output
[1,2,3,4,5]
Explanation

Remove all 6s

Algorithm Flow

Recommendation Algorithm Flow for Remove Elements
Recommendation Algorithm Flow for Remove Elements

Solution Approach

Filter the array to keep only elements that do not match the target value.

function solution(arr, val) {
  var r = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] !== val) r.push(arr[i]);
  }
  return r;
}

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

java
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;
    }
}