# Rotate String – HackerRank Solution

In this post, we will solve Rotate String HackerRank Solution. This problem (Rotate String) is a part of HackerRank Functional Programming series.

Scturtle likes strings very much. He is getting bored today, because he has already completed this week’s task and doesn’t have anything else to do. So he starts left-rotating a string. If the length of the string isÂ n, then he will rotate itÂ nÂ times and note down the result of each rotation on a paper.

For a stringÂ S = s1 s2 . . . sn, nÂ rotations are possible. Let’s represent these rotations byÂ r1, r2 . . . rn. Rotating it once will result in stringÂ r1 = s2s3 . . . sns1, rotating it again will result in stringÂ r2 = s3s4 . . . sns1s2Â and so on. Formally,Â ithÂ rotation will be equal toÂ ri = si+1 . . . sn-1 sn s1 . . . si. Note thatÂ rn = S.

For example, ifÂ SÂ =Â `abc`Â then it has 3 rotations. They areÂ r1Â =Â `bca`,Â r2Â =Â `cab`Â andÂ r3Â =Â `abc`.

## Input Format

The first line contains an integer,Â T, which represents the number of test cases to follow. Then followsÂ TÂ lines, which represent a test case each.
Each test case contains a string,Â S, which consists of lower case latin charactersÂ (‘a‘ – ‘z‘)Â only.

## Output Format

For each test case, print all the rotations,Â r1 r2 . . . rn, separated by a space.

## Constraints

• 1 <= T <= 10
• 1 <= n <= 102
• SÂ will consist of lower case latin character,Â [‘a‘ . . . ‘z‘]Â only.

Sample Input

``````5
abc
abcde
abab
aaa
z``````

Sample Output

``````bca cab abc
bcdea cdeab deabc eabcd abcde
baba abab baba abab
aaa aaa aaa
z``````

Explanation

Test case #1:Â This case is mentioned in the problem statment.
Test case #2:Â Rotations ofÂ `abcde`Â are:Â `bcdea`Â ->Â `cdeab`Â ->Â `deabc`Â ->Â `eabcd`Â ->Â `abcde`.
Test case #3:Â Rotations ofÂ `abab`Â are:Â `baba`Â ->Â `abab`Â ->Â `baba`Â ->Â `abab`.
Test case #4:Â All three rotations will result into same string.
Test case #5:Â Only one rotation is possible, and that will result into original string.

## Solution – Rotate String – HackerRank Solution

Scala

```import java.util.Scanner

object Solution {

def main(args: Array[String]): Unit = {
val sc = new Scanner(System.in)

val t = sc.nextInt
sc.nextLine

(0 until t).foreach(_ => {
val s = sc.nextLine

case class Acc(s: String, answer: List[String])
println((0 until s.length).foldLeft(Acc(s, Nil))((acc, _) => {
val nextV = acc.s.tail + acc.s.head