I started with the standard reverse-sublist approach and felt pretty confident until they asked about the head case.
First, traverse the list to locate the first and second occurrences of v, keeping track of the node before the first occurrence (prev_first) and the node after the second occurrence (after_second). Then, reverse the sublist from the first to the second occurrence using the standard iterative three-pointer technique, and reconnect the reversed sublist with prev_first and after_second. Finally, handle edge cases by checking if prev_first is null (sublist starts at head) or if after_second is null (sublist ends at tail) and adjust the head pointer accordingly.
Pro tip: Clarify with the interviewer whether the value v is guaranteed to appear at least twice (as stated) and whether the list can be modified in-place. Also, mention that you would test with edge cases like adjacent occurrences, sublist at head/tail, and list length exactly two.
Traverse the list to locate the first and second nodes with value v. Keep track of the node before the first occurrence (prev_first) and the node after the second occurrence (after_second).
Reverse the sublist from the first to the second occurrence using iterative pointer manipulation. Maintain prev, curr, and next pointers to reverse links without extra space.
Connect prev_first to the new head of the reversed sublist (which was the second occurrence) and connect the new tail (which was the first occurrence) to after_second.
If prev_first is null, update the head to point to the new head of the reversed sublist. If after_second is null, ensure the new tail's next is null. For adjacent nodes, the reversal is trivial but still handled by the same logic.
Explain that the algorithm traverses the list at most twice, so time complexity is O(n). Space complexity is O(1) because only a constant number of pointers are used.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.