Filter Alternate Nodes in a Sequence
Linked ListsAuto-graded · 17 test casesLast updated
Tests the ability to process a linear collection by dropping elements at even 1-based index positions.
Given a list of values representing a sequence, return a new list containing only the elements located at odd 1-based positions (1st, 3rd, 5th, etc.). Every element at an even 1-based position (2nd, 4th, 6th, etc.) must be removed.
Constraints
- $0 \le n \le 1{,}000{,}000$, where $n$ is the length of
values. - Elements can be any valid integers.
- The relative order of the remaining elements must be preserved.
Examples
Example 1
Input: remove_even_positioned_nodes([1, 2, 3, 4, 5])
Output: [1, 3, 5]
Example 2
Input: remove_even_positioned_nodes([10, 20])
Output: [10]
Example 3
Input: remove_even_positioned_nodes([7, 8, 9, 10, 11, 12])
Output: [7, 9, 11]
Hints
Hint 1
Consider 1-based vs 0-based indexing: 1-based positions 1, 3, 5, ... correspond to 0-based indices 0, 2, 4, ...
Hint 2
You can achieve this in Python using list slicing or a simple loop that increments the index by 2 at each step.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task requires selecting elements at odd 1-based positions (1st, 3rd, 5th, etc.) and skipping even 1-based positions (2nd, 4th, 6th, etc.).
In 0-based indexing, this corresponds to taking elements at indices $0, 2, 4, 6, \dots$.
In Python, this operation can be succinctly performed using extended slicing: values[::2], which steps through the sequence with a stride of 2 starting from index 0.
Complexity
- Time Complexity: $\mathcal{O}(n)$, where $n$ is the length of the input list
values. Each kept element is visited and copied once. - Space Complexity: $\mathcal{O}(n)$ auxiliary space to allocate the output list containing $\lceil n / 2 \rceil$ elements.
Reference Solution
from typing import List
def remove_even_positioned_nodes(values: List[int]) -> List[int]:
return values[::2]