U

26. Rotate Array One Position Left and Right

Easy

Problem Description

Given an array of NN integers:

  1. 1.Print the array rotated one position to the left (first element moves to the end).
  2. 2.Print the original array rotated one position to the right (last element moves to the front).

Input Format

  • •Line 1: An integer NN (1≤N≤1051 \le N \le 10^5).
  • •Line 2: NN space-separated integers A1,A2,…,ANA_1, A_2, \dots, A_N.

Output Format

  • •Line 1: NN space-separated integers after 1-position left rotation.
  • •Line 2: NN space-separated integers after 1-position right rotation.
Example 1:
Input:
5
1 2 3 4 5
Output:
2 3 4 5 1
5 1 2 3 4
Explanation: Left rotate moves 1 to back. Right rotate moves 5 to front.
Example 2:
Input:
1
42
Output:
42
42
Explanation: Single element remains same in both rotations.
Example 3:
Input:
3
10 20 30
Output:
20 30 10
30 10 20
Explanation: Left: 20 30 10. Right: 30 10 20.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online