All challenges
Easy 0 solved 0% acceptance

Swap First and Last

Exchange the first and last items of a list.

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

Example 1
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].

Example 2
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].

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.