1. Array Value Extraction and Sub-Array Reversal
Intuition
1. Collect node pointers or values into an array vals.
2. Reverse vals[left-1 .. right-1] using standard two pointers.
3. Traverse the linked list again, overwriting node.val with vals[i].
When to apply: Quick solution when value modification is acceptable or pointers are confusing.
Algorithm
- Traverse linked list and collect values in dynamic array.
- Reverse array elements in range [left - 1, right - 1].
- Traverse linked list again and write updated values.
#include <iostream>#include <vector>#include <algorithm> struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {}}; class Solution {public: ListNode* reverseBetween(ListNode* head, int left, int right) { std::vector<int> vals; ListNode* curr = head; while (curr != nullptr) { vals.push_back(curr->val); curr = curr->next; } std::reverse(vals.begin() + left - 1, vals.begin() + right); curr = head; for (int v : vals) { curr->val = v; curr = curr->next; } return head; }}; int main() { ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); Solution sol; ListNode* res = sol.reverseBetween(head, 2, 4); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Pass 1 extracts N values, reversing sub-array takes (right - left) / 2 steps, and pass 2 writes N values: O(N) overall. - Space complexity:
O(N)— Stores N values in an auxiliary array: O(N) extra space.