Cyclic Message Rotation — Problem Statement & Solution Guide
Problem Description
Given an array of strings messages and an integer shifts, cyclically rotate the elements in messages to the right by shifts positions and return the resulting array.
Examples
Input
['hello', 'abc', 'world']
Output
['world', 'abc', 'hello']
Explanation: Step 1: Given array ['hello', 'abc', 'world'] and shift 2. Step 2: Rotate the last 2 elements 'world' and 'abc' to the front of the array. Step 3: The resulting array is ['world', 'abc', 'hello']
Input
['hello', 'abc', 'world']
Output
['world', 'hello', 'abc']
Explanation: Step 1: Given array ['hello', 'abc', 'world'] and shift 1. Step 2: Rotate the last 1 element 'world' to the front of the array. Step 3: The resulting array is ['world', 'hello', 'abc']
Constraints
- 1 <= number of messages <= 100
- 0 <= number of shifts <= 1000
Optimal Approach & Strategy
The optimal approach involves utilizing the modulo operator to determine the effective number of shifts and then using array slicing to rotate the messages in a single operation, resulting in a time complexity of O(n).
Brute Force Approach
A naive approach would involve shifting the messages one step to the right for the specified number of shifts, resulting in a time complexity of O(n*shifts). This could be achieved through a simple loop. However, this is inefficient for large inputs.
Verified Code Solutions
function cyclicMessageRotation(messages, shifts) { return messages.slice(-shifts).concat(messages.slice(0, -shifts)); }class Solution {
public String[] cyclicMessageRotation(String[] messages, int shifts) {
shifts = shifts % messages.length;
String[] result = new String[messages.length];
System.arraycopy(messages, messages.length - shifts, result, 0, messages.length - shifts);
System.arraycopy(messages, 0, result, messages.length - shifts, shifts);
return result;
}
}def cyclic_message_rotation(messages, shifts):
shifts = shifts % len(messages)
return messages[-shifts:] + messages[:-shifts]function cyclicMessageRotation(messages, shifts) { return messages.slice(-shifts).concat(messages.slice(0, -shifts)); }Asked in Top Tech Interviews
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.