Problem
Return a copy of the list with its first and last elements swapped. Lists with fewer than two elements stay the same.
Implement swap_first_last(items).
Input
items: The list of integers.
Output
Return the list with the ends swapped.
Constraints
0 ≤ length ≤ 100,000
Examples
Input:
items = [1, 2, 3, 4]
Expected output:
expected = [4, 2, 3, 1]
Input:
std::vector<long long> items = {1, 2, 3, 4};
Expected output:
std::vector<long long> expected = {4, 2, 3, 1};
Input:
long[] items = new long[] {1, 2, 3, 4};
Expected output:
long[] expected = new long[] {4, 2, 3, 1};
Explanation
1 and 4 trade places: [4, 2, 3, 1].
Input:
items = [9]
Expected output:
expected = [9]
Input:
std::vector<long long> items = {9};
Expected output:
std::vector<long long> expected = {9};
Input:
long[] items = new long[] {9};
Expected output:
long[] expected = new long[] {9};
Explanation
A single item has nothing to swap with: [9].
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
Only the two ends need to change; everything in the middle stays untouched.
Hint 2
Build a new list by keeping the middle section and placing the last item first, then the first item last.
Hint 3
Remember the empty and one-element cases should be returned unchanged.
Expected complexity
O(n) time, O(n) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.