BackmediumBacktrackinguncategorizedmedium

Circular Array Shift Solution

Problem Statement

You are given an array of integers elements with length n and a non-negative integer shifts. Your task is to perform a right rotation on the array by shifts positions. A right rotation by one position moves the last element to the front and shifts all other elements one position to the right. If shifts is greater than or equal to n, the effective rotation is determined by shifts % n.

Implement a function that returns the resulting array after applying the specified rotation. The operation must be efficient, ideally in O(n) time complexity, and should handle edge cases such as zero shifts or shifts equal to the array length correctly.

Example 1
Input
elements = [1, 2, 3, 4, 5], shifts = 2
Output
[4, 5, 1, 2, 3]

Explanation: The array length is 5. Shifting right by 2 positions means the last 2 elements [4, 5] move to the front. The remaining elements [1, 2, 3] follow. Result: [4, 5, 1, 2, 3].

Example 2
Input
elements = [10, 20, 30], shifts = 1
Output
[30, 10, 20]

Explanation: The array length is 3. Shifting right by 1 position moves the last element 30 to the front. The elements [10, 20] shift right. Result: [30, 10, 20].

Example 3
Input
elements = [7, 8, 9, 10], shifts = 6
Output
[9, 10, 7, 8]

Explanation: The array length is 4. Since shifts = 6, the effective shift is 6 % 4 = 2. Shifting right by 2 positions moves the last 2 elements [9, 10] to the front. The remaining elements [7, 8] follow. Result: [9, 10, 7, 8].

Example 4
Input
elements = [1, 1, 1, 1], shifts = 3
Output
[1, 1, 1, 1]

Explanation: The array length is 4. Shifting right by 3 positions is equivalent to shifting left by 1 position. Since all elements are identical, the array remains unchanged. Result: [1, 1, 1, 1].

Constraints

  • 1 <= elements.length <= 10^5
  • -10^9 <= elements[i] <= 10^9
  • 0 <= shifts <= 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Circular Array Shift — Problem Statement & Solution Guide

BacktrackingMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

You are given an array of integers elements with length n and a non-negative integer shifts. Your task is to perform a right rotation on the array by shifts positions. A right rotation by one position moves the last element to the front and shifts all other elements one position to the right. If shifts is greater than or equal to n, the effective rotation is determined by shifts % n.

Implement a function that returns the resulting array after applying the specified rotation. The operation must be efficient, ideally in O(n) time complexity, and should handle edge cases such as zero shifts or shifts equal to the array length correctly.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Circular Array Shift"

medium

WHY DOES IT MATTER?

The rotation pattern exemplifies in‑place permutation, a fundamental skill for optimizing memory‑constrained systems. Mastery of this pattern prevents unnecessary allocations and reduces runtime, which is critical in high‑throughput services and embedded environments.

OPTIMIZATION CHALLENGE

The key insight is to treat the array as a circle and use reversal to reposition segments in linear time. By reversing the whole array first, we bring the target segment to the front in reversed order, then a second reversal restores its correct orientation.

REAL-WORLD CONNECTION

Think of a circular buffer used in network packet queues: when the write pointer reaches the end, it wraps around to the start. Rotating an array mimics this wrap‑around behavior, allowing constant‑time access to the most recent elements without moving data physically.

During an interview, write the three‑step reversal code first, then explain why each reverse is necessary. This demonstrates both implementation skill and deep conceptual understanding, which interviewers love.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

Rotating an array is a classic example of in‑place permutation. The naive method copies each element to a new array or repeatedly shifts elements one by one, leading to O(n·shifts) time, which becomes prohibitive when both n and shifts are large (e.g., n = 10^6, shifts = 10^9). The optimal solution leverages the mathematical property that a right rotation by k positions is equivalent to a left rotation by n‑k, and that the effective shift count is k % n. By treating the array as a circular buffer, we can achieve the rotation using three reversals: reverse the whole array, reverse the first k elements, then reverse the remaining n‑k elements. This approach runs in linear time O(n) and uses O(1) extra space, satisfying the constraints of most interview problems.

The three‑step reversal works because reversing the entire array flips the order of elements, placing the segment that should end up at the front (the last k elements) in reverse order at the beginning. Re‑reversing each segment restores their internal order while preserving the overall rotation. This technique is a specific instance of the broader "reverse‑then‑reverse‑segments" pattern used for many in‑place array transformations, such as left rotations, array shuffling, and even string manipulations. Understanding this pattern equips candidates to solve a wide range of permutation problems efficiently.

Interview Questions on This Problem

Q1How would you rotate an array of size 10^7 by 10^12 positions without using extra memory?

First compute effectiveShift = shifts % n. Then apply the three‑step reversal algorithm: reverse the whole array, reverse the first effectiveShift elements, and finally reverse the remaining n‑effectiveShift elements. This runs in O(n) time and O(1) extra space.

Q2Can you modify the rotation algorithm to work on a singly linked list?

Yes. Find the (n‑k)th node, break the list after it, and connect the tail to the original head. Finally, set the new head to the (n‑k+1)th node. This requires a single traversal to locate the split point, achieving O(n) time and O(1) extra space.

Q3Why is it safe to ignore rotations where shifts >= n and simply use shifts % n?

Because rotating by n positions returns the array to its original configuration; rotations are periodic with period n. Therefore any number of shifts can be reduced modulo n without changing the final arrangement.

Examples

Example 1

Input

elements = [1, 2, 3, 4, 5], shifts = 2

Output

[4, 5, 1, 2, 3]

Explanation: The array length is 5. Shifting right by 2 positions means the last 2 elements [4, 5] move to the front. The remaining elements [1, 2, 3] follow. Result: [4, 5, 1, 2, 3].

Example 2

Input

elements = [10, 20, 30], shifts = 1

Output

[30, 10, 20]

Explanation: The array length is 3. Shifting right by 1 position moves the last element 30 to the front. The elements [10, 20] shift right. Result: [30, 10, 20].

Example 3

Input

elements = [7, 8, 9, 10], shifts = 6

Output

[9, 10, 7, 8]

Explanation: The array length is 4. Since shifts = 6, the effective shift is 6 % 4 = 2. Shifting right by 2 positions moves the last 2 elements [9, 10] to the front. The remaining elements [7, 8] follow. Result: [9, 10, 7, 8].

Example 4

Input

elements = [1, 1, 1, 1], shifts = 3

Output

[1, 1, 1, 1]

Explanation: The array length is 4. Shifting right by 3 positions is equivalent to shifting left by 1 position. Since all elements are identical, the array remains unchanged. Result: [1, 1, 1, 1].

Constraints

  • 1 <= elements.length <= 10^5
  • -10^9 <= elements[i] <= 10^9
  • 0 <= shifts <= 10^9

Optimal Approach & Strategy

Compute k = shifts % n and apply the three‑step in‑place reversal: reverse whole array, reverse first k elements, reverse the rest. This achieves linear time with constant extra space.

Brute Force Approach

Repeatedly shift the array one position to the right for each rotation, or copy elements into a new array using the formula new[i] = old[(i‑k+n)%n].

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(elements, shifts) {
   let n = elements.length;
   shifts = shifts % n;
   let result = elements.slice(-shifts).concat(elements.slice(0, -shifts));
   return result;
}

Asked in Top Tech Interviews

uncategorizedmediumgeneric

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.