You are viewing a single comment's thread. Return to all comments →
That's not the aim of the exercise... You have to fill the array and after shift!!! In this way is easy and you are not resolving the left shift problem.
For me, it's just an alternative way. There's not only one way to think for the same problem whatever the solution is good or bad. I shared my solution because I hadn't seen anyone think the same way and I thought it was good to learn from people's comments on my solution.
A good solution by you!
I like your solution, elegant and efficient. It took my two days for mine and even now has timeout issues when testing. I have good envy now. Well done!
I really like your solution as you have reduce the time complexity to O(n^2) while is very efficeint compare to my program which has a T(n) = O(n^3)
How the complexity is quadratic? It is O(n), right?
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 :)
this is the simplest and most efficient solution. I was struggling Time out error with mine.
It's the far superior solution. Why shift all the elements in the array individually, when you can just shift the index to achieve the same result? It's a total waste of processing to shift the entire array. What if the array was 1,000,000,000 elements long, and you had to shift multiple times? In an interview they would probably expect you to do it this way, with an explanation of your logic.
I agree. If they wanted something to shift elements of an array, they should have asked for a function to do so.
In my case, they were expecting the function that returns a vector with all the elements rotated any number of times. So, the best way is to take the number of shiftings and move the index that number of times, and do the shift only one time.