← Questions
Reverse a linked list between nodes with equal values
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Sep 2025. It tests linked lists.
Given a singly linked list and a value v, find the first two nodes that hold v (call them A and B, A first) and reverse, in place, the nodes strictly between them. A and B stay where they are. If fewer than two nodes hold v, leave the list unchanged.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
reverse_between_values(head: ListNode | None, v: int) -> ListNode | None— returns the head, which never changes here because A and B stay in place.
Example
Lists written head to tail:
reverse_between_values([1, 5, 2, 3, 4, 5, 9], 5) -> [1, 5, 4, 3, 2, 5, 9]
reverse_between_values([5, 5, 7], 5) -> [5, 5, 7] # A and B adjacent
reverse_between_values([3, 1, 2], 7) -> [3, 1, 2] # no 7 at all
reverse_between_values([7, 1, 2, 7, 3, 4, 7], 7) -> [7, 2, 1, 7, 3, 4, 7] # only the first pair
Constraints
-
0 <= n <= 10^5. Values fit in 32-bit integers and may repeat. - One pass and O(1) extra space if you can.
Clarifying questions
- Which pair of
vnodes: the first two, or every consecutive pair? - Do A and B themselves move, or only the nodes between them?
- What if A and B are adjacent, or
vappears only once?
What a strong answer covers
- Walk to A, then reverse nodes one by one until you reach a node with value
v(B), then reconnect A to the new first node and the old first node to B. - Handling "B never appears": you only find out at the end, so either undo the partial reversal or find B before reversing anything (two passes, still O(1) space).
- O(n) time, O(1) space, and pointer bookkeeping explained with a drawing.
- Tests: empty list, a single
v, adjacentvnodes,vat the head and at the tail, three or morevnodes.
Follow-ups
- Reverse between every consecutive pair of
vnodes (A to B, then B to C, and so on). - Include A and B in the reversed part.
- Reverse the sublist between positions
leftandright.
Where it's asked
- Meta · Technical phone screen · Last asked Sep 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
linked lists
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
