All challenges
Easy 0 solved 0% acceptance

Swap First and Last

Exchange the first and last items of a list.

What you'll learn

  • Access the first and last items
  • Swap two values
  • Handle short lists

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

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.

Learn from others

Community solutions

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