Swap Nodes in Pairs
Updated
Problem statement
You are given the head of a singly linked list. Group the nodes in pairs from the front: the 1st and 2nd nodes, then the 3rd and 4th, and so on. Swap the two nodes in every pair, and return the head of the new list.
If the list has an odd number of nodes, the last node has no partner and stays where it is. An empty list stays empty.
Change the links between nodes instead of copying values from one node to another. The judge reads the values from head to tail and compares their order.
Function
swapPairs(head: ListNode) → ListNodeExamples
Example 1
head = [3,8,5,2]return = [8,3,2,5]The pairs are (3, 8) and (5, 2). Swapping inside each pair gives [8, 3, 2, 5].
Example 2
head = [7,8,9,10,11]return = [8,7,10,9,11]The pairs are (7, 8) and (9, 10). They swap to 8, 7, 10, 9.
The fifth node, 11, has no partner, so it stays last. The answer is [8, 7, 10, 9, 11].
Example 3
head = [-5]return = [-5]One node cannot form a pair, so the list does not change. The answer is [-5].
Example 4
head = [10,20]return = [20,10]The only pair is (10, 20). Swapping it gives [20, 10].
Constraints
- The list has between
0and1000nodes. -1000 <= node.val <= 1000
More Bloomberg LP Onsite Interview questions
- N-ary Index-Path Encoder and DecoderPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Top K Frequent WordsONSITE INTERVIEW · Seen Nov 2026
- Trapping Rain WaterPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Word SearchOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Design Browser HistoryPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Mutable Stock Price Top KPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Add Two Numbers IIPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Decode StringPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Minimum Replacements to Make Two Strings AnagramsPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Currency Conversion RatePHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- LRU Cache for Query ResultsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- LRU CacheServiceNow · PHONE SCREEN · ONSITE INTERVIEWServiceNow interview questions
- Reverse a Sublist of a Linked ListSalesforce · ONSITE INTERVIEWSalesforce interview questions
- LRU CacheLotusFlare · ONSITE INTERVIEW
- LRU CacheGimlet Labs · PHONE SCREEN
- Remove Nth Node From End of ListDruva · ONSITE INTERVIEW
- Merge a List In Between Two PositionsWalmart · ONSITE INTERVIEWWalmart interview questions
- LRU CacheBNSF Railway · PHONE SCREENBNSF Railway interview questions
- LRU CacheJP Morgan Chase · ONSITE INTERVIEWJP Morgan Chase interview questions
- LRU Cache OperationsHevo Data · ONSITE INTERVIEW