We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

This solution will not work when rotation is greater than array size, meaning d > n. Java returns negative result if you perform % operation on a negative number. And that negative number will throw an

java.lang.ArrayIndexOutOfBoundsException

Eg. n = 4, d = 7

Starting with i=0,
a[(i+n-d)%n] will give
a[(0 + 4 - 7)%4] => a[(0 + (-3))%4] => a[(-3)%4] => a[-3]

## Left Rotation

You are viewing a single comment's thread. Return to all comments →

This solution will not work when rotation is greater than array size, meaning d > n. Java returns negative result if you perform % operation on a negative number. And that negative number will throw an

Eg. n = 4, d = 7

Starting with i=0, a[(i+n-d)%n] will give a[(0 + 4 - 7)%4] => a[(0 + (-3))%4] => a[(-3)%4] => a[-3]

Range of a is from 0 to n. Hence the error

for this case you can check for d>n and d = d%n then d will be in range of 0 to n and the above solution will work perfectly :)