BackmediumArraysRazorpay

Cyclic Message Rotation Solution

Problem Statement

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.

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

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

Cyclic Message Rotation — Problem Statement & Solution Guide

ArraysMediumString Manipulation
TimeO(n)
|
SpaceO(n)

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

Example 1

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

Example 2

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

JavaScript Solution
Time: O(n)
function cyclicMessageRotation(messages, shifts) { return messages.slice(-shifts).concat(messages.slice(0, -shifts)); }

Asked in Top Tech Interviews

Razorpay

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.