Reverse even numbers in a list
Company: Upstart
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates competency in basic array manipulation, specifically filtering elements by parity and reversing their order while preserving no other ordering constraints.
Constraints
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Examples
Input: ([2, 3, 4],)
Expected Output: [4, 2]
Explanation: Scanning right-to-left: 4 (even, keep), 3 (odd, skip), 2 (even, keep) -> [4, 2].
Input: ([],)
Expected Output: []
Explanation: Empty input yields an empty result.
Input: ([1, 3, 5, 7],)
Expected Output: []
Explanation: No even numbers, so the result is empty.
Input: ([0, 2, 4, 6],)
Expected Output: [6, 4, 2, 0]
Explanation: All even; reversed order is 6, 4, 2, 0. Note 0 is even.
Input: ([2, 2, 3, 2],)
Expected Output: [2, 2, 2]
Explanation: Duplicate evens are all kept; the odd 3 is removed.
Input: ([-4, -3, -2, 1],)
Expected Output: [-2, -4]
Explanation: Negative evens count: right-to-left gives -2, then -4.
Input: ([5],)
Expected Output: []
Explanation: Single odd element produces an empty result.
Input: ([8],)
Expected Output: [8]
Explanation: Single even element is returned as-is.
Hints
- Iterate over the array from the last element to the first.
- Keep only the values that are divisible by 2 (use the modulo operator: x % 2 == 0). Remember that 0 and negative numbers can be even too.
- Equivalently, filter the evens first then reverse the result — both give the same order.