Swap Linked List Nodes in Pairs
Updated
Problem statement
You are given the head of a singly linked list. Swap every two neighbouring nodes, starting from the head: the 1st node with the 2nd, the 3rd with the 4th, and so on. If the list has an odd number of nodes, the last node has no partner and stays at the end.
Return the head of the changed list.
Move the nodes themselves by changing their next links. In an interview, swapping only the values inside the nodes is usually not accepted. The judge checks the order of the values in the list you return.
Function
swapPairs(head: ListNode) → ListNodeExamples
Example 1
head = [1,2,3,4]return = [2,1,4,3]Moved or new
The pairs are (1,2) and (3,4). Swapping each pair gives [2,1,4,3].
Example 2
head = [5,6,7]return = [6,5,7]Moved or new
The first pair (5,6) becomes (6,5). The last node, 7, has no partner, so it stays at the end.
Example 3
head = []return = []An empty list has nothing to swap, so the answer is the empty list.
Constraints
- The number of nodes in the list is between
0and500. -10^4 <= Node.val <= 10^4
More Expedia Onsite Interview questions
- Scramble StringONSITE INTERVIEW · Seen Sep 2026
- Smallest Sufficient TeamONSITE INTERVIEW · Seen Sep 2026
- Check Anagram Pairs Index by IndexONSITE INTERVIEW · Seen Oct 2025
- Fresh Oranges Left After Rotting StopsONSITE INTERVIEW · Seen Oct 2025
- Longest Increasing SubsequenceONSITE INTERVIEW · Seen Oct 2025
- Lowest Common Ancestor with Repeated and Missing ValuesONSITE INTERVIEW · Seen Oct 2025
- Shortest Substring with Exactly K OnesONSITE INTERVIEW · Seen Oct 2025
- Middle Element of a Linked ListONSITE INTERVIEW · Seen Nov 2024
- Minimum in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Sep 2024
- Mirror Image Binary TreesONSITE INTERVIEW · Seen Sep 2024
Similar questions at other companies
- Reverse a Sublist of a Linked ListSalesforce · ONSITE INTERVIEWSalesforce interview questions
- LRU CacheLotusFlare · ONSITE INTERVIEW
- LRU Cache for Query ResultsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Remove Nth Node From End of ListDruva · ONSITE INTERVIEW
- Merge a List In Between Two PositionsWalmart · ONSITE INTERVIEWWalmart interview questions
- LRU CacheJP Morgan Chase · ONSITE INTERVIEWJP Morgan Chase interview questions
- LRU Cache OperationsHevo Data · ONSITE INTERVIEW
- LRU Cache OperationsLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- First-Fit Memory AllocatorGoogle · ONSITE INTERVIEWGoogle interview questions
- Find the Entry of a Linked List CycleQualys · ONSITE INTERVIEWQualys interview questions
Interview reports that mention this question
Expedia interview experiences
- Expedia Intern Final Round in 2021: 28 Experiences (Part 4 of 6)
- Expedia Intern Finals Before 2020: 14 Experiences (Part 6 of 6)
- Expedia Intern Final Round in 2020: 24 Experiences (Part 5 of 6)
- Expedia Intern Final Round in 2022: 15 Experiences (Part 3 of 6)
- Expedia SWE Intern Final Round: 126 Experiences (Part 1 of 6)