Reverse between equal-value nodes in list
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to manipulate singly linked lists, perform in-place sublist reversal, and manage pointer references and node boundaries.
Constraints
- 0 <= len(values) <= 10^5
- Node values fit in a 32-bit signed integer (may be negative).
- Use the first two nodes whose value equals v as the boundaries A and B.
- If fewer than two nodes equal v, return the list unchanged.
- Aim for a single pass and O(1) extra space.
Examples
Input: ([1, 5, 2, 3, 4, 5, 9], 5)
Expected Output: [1, 5, 4, 3, 2, 5, 9]
Explanation: A=index 1, B=index 5; interior [2,3,4] reverses to [4,3,2].
Input: ([5, 5, 7], 5)
Expected Output: [5, 5, 7]
Explanation: A and B are adjacent (indices 0 and 1); nothing strictly between them, so the list is unchanged.
Input: ([5, 1, 2, 5], 5)
Expected Output: [5, 2, 1, 5]
Explanation: Interior [1,2] reverses to [2,1]; boundary 5's stay put.
Input: ([1, 2, 3], 9)
Expected Output: [1, 2, 3]
Explanation: No node equals 9, so fewer than two occurrences exist; unchanged.
Input: ([7], 7)
Expected Output: [7]
Explanation: Only one node equals 7; fewer than two occurrences, unchanged.
Input: ([], 4)
Expected Output: []
Explanation: Empty list stays empty.
Input: ([3, 8, 3, 8, 3], 3)
Expected Output: [3, 8, 3, 8, 3]
Explanation: First two 3's are at indices 0 and 2; only index 1 lies between them, so the single-element interior is unchanged. Later occurrences of 3 are ignored.
Input: ([4, 1, 4, 2, 4], 4)
Expected Output: [4, 1, 4, 2, 4]
Explanation: First two 4's at indices 0 and 2; single interior node [1] unchanged. The third 4 is ignored.
Input: ([-1, 0, 5, -1, 9, -1], -1)
Expected Output: [-1, 5, 0, -1, 9, -1]
Explanation: Negative target; A=0, B=3, interior [0,5] reverses to [5,0]. The third -1 is ignored.
Hints
- Scan once and record the index of the first node equal to v, then the index of the second. If you never find a second one, return the list as-is.
- Only the nodes strictly between those two indices move; the two boundary nodes stay where they are.
- Reverse the interior by swapping from both ends toward the middle (two pointers), which keeps extra space at O(1).
- Watch the adjacent case: if the two boundary indices differ by 1, there is no interior to reverse — the list is unchanged.