BackmediumArraysZomatoAccenture

Minimized Rotation String Solution

Problem Statement

Given a non-empty string source and an integer rotations, find the lexicographically smallest string that can be obtained by performing rotations number of rotations on the source string. A single rotation involves moving the last character of the string to the front.

Example 1
Input
source = 'abcdef', rotations = 1
Output
efabcd

Explanation: To find the lexicographically smallest string after rotations, we first perform the given number of rotations on the source string. In this case, we rotate 'abcdef' once, resulting in 'efabcd'.

Example 2
Input
source = 'aaa', rotations = 1
Output
aaa

Explanation: Since 'aaa' is already the lexicographically smallest string, we return 'aaa' as the result. Note that it's already smallest, not that it's the same after rotation.

Constraints

  • 1 ≤ length of string ≤ 10^5
  • 1 ≤ k ≤ 10^6
  • String contains only lowercase English letters
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

Minimized Rotation String — Problem Statement & Solution Guide

ArraysMediumString Manipulation
TimeO(n)
|
SpaceO(1)

Problem Description

Given a non-empty string source and an integer rotations, find the lexicographically smallest string that can be obtained by performing rotations number of rotations on the source string. A single rotation involves moving the last character of the string to the front.

Examples

Example 1

Input

source = 'abcdef', rotations = 1

Output

efabcd

Explanation: To find the lexicographically smallest string after rotations, we first perform the given number of rotations on the source string. In this case, we rotate 'abcdef' once, resulting in 'efabcd'.

Example 2

Input

source = 'aaa', rotations = 1

Output

aaa

Explanation: Since 'aaa' is already the lexicographically smallest string, we return 'aaa' as the result. Note that it's already smallest, not that it's the same after rotation.

Constraints

  • 1 ≤ length of string ≤ 10^5
  • 1 ≤ k ≤ 10^6
  • String contains only lowercase English letters

Optimal Approach & Strategy

The optimized approach involves concatenating the input string with itself and finding the smallest substring of the same length as the input string, resulting in a time complexity of O(n).

Brute Force Approach

The brute-force approach involves rotating the string k times, which results in a time complexity of O(n*k) where n is the length of the string.

Verified Code Solutions

No solution currently available for JavaScript. Select another language tab above.

Asked in Top Tech Interviews

ZomatoAccenture

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.