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.
Each time I read an element of the array from the input, I directly assign it to the array at the speific index after shifting. d left rotations equal (n-d) right rotations. The array has a size of n, so when the index (i+n-d) is equal to n, the index actually goes back to the starting index. I use mod to get the correct index where I want to assign the element when the index is larger than n. I'm not an english native speaker. Hope you will understand what I explain. :)
I see a problem here. You've assumed that we can sort the array at the time of initialization itself. Though it's good, but IMHO, the real test is to sort an already existing array with space constraints.
I'm failing to see where it actually does a left rotate of an existing array.
What I'm seeing is (from assumption of ...)
array[0..n] is empty initially.
getArray[0..n] stores input from stdin.
store rotated result into array[0..n].
The existing array is getArray. That array is still in an unrotated order. The array[0..n] isn't considered the exiting array as it is empty.
Challenge to you: get rid of getArray array and store input into array[] array. Rotate that array and then print the end result of that array.
This code is actually quite efficient. So for the following values, n=5 (number of elements in the array), d=2 (number of rotations)and assuming i goes from 0-4.
(i + n - d)%n with the iteration of i from 0-4:
(0+5-2)%5=3
(1+5-2)%5=4
.
.
.
(4+5-2)%5=2
So essentially, you are changing the locations of the elements in the array. How the "%" works is that it takes the remainder. So for example, 1%7=1 since 1 cannot be divided by 7 which means 1 is the remainder.
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.
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!
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]
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.
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.
Have you tried running this? You actually run into an issue where you just propagate the first value in the array across all other indices in the array using your method.
The second for loop moves the value at index 0, the 1, over to index 1, overwriting the value 2 at index 1, and then this 1 gets written into all the other indices as a result.
Solid answer.
I would like to point out to people that this does require double the memory of the intial answer as this requires a second array to store all the properly ordered array.
If you're on a memory tight situation, this would not be a favorable solution.
To solve this, I've shifted the elements in the array in O(n) time and O(n) memory (vs O(2n)). Not as easy on the eyes, though :(
functionprocessData(input){// get `n` and `d` from inputconstlines=input.split('\n');constfirstLine=lines[0].split(' ').map(Number);constn=firstLine[0];constd=firstLine[1];// process each linelines.slice(1,lines.length).forEach(line=>{// no need to shift in these casesif(n===1||d===n){console.info(line);}else{// shift digitsconsta=line.split(' ').map(Number);letlastLastItem=null;letcount=0;leti=0;while(count<n){i++;conststart=i;letj=start;do{count++;letlastItem=lastLastItem;lastLastItem=a[j];a[j]=lastItem;j=shiftLeft(n,d,j);}while(j!==start);a[start]=lastLastItem;}console.info(a.reduce((acc,value)=>{returnacc+' '+value;}));}});}/** * @param {Number} n total number of elements * @param {Number} d number of shifts to left * @param {Number} i index to begin shifting from * @returns {Number} new index after shifting to left */functionshiftLeft(n,d,i){return(n-d+i)%n;}
I'm ignoring the processing time on input string manipulation and such. This examples assumes they gave us an existing array to manipulate.
Hey! Could you include comments in your code please? I use C and dont kow other language as of now but would like to learn from your solution O(n) is preety nice
Solution.cpp:1:1: error: ‘function’ does not name a type; did you mean ‘union’?
function processData(input) {
^~~~~~~~
union
Solution.cpp:45:1: error: ‘function’ does not name a type; did you mean ‘union’?
function shiftLeft(n, d, i) {
^~~~~~~~
union
Revisited this with an easier-on-the-eyes solution that finishes in O(n) time with O(n) memory.
functionmain(){// ...loopUntilAllSwapped(a,d);console.log(a.join(' ')+'\n');}/** * If a.length can be divided by d evenly, swapSeries will end * where it started without swapping all numbers. * This function ensures that all numbers are swapped. * * Variables: * a: array of numbers * d: number of left-rotations to perform * c: count of numbers swapped * i: index to start swapSeries() from */functionloopUntilAllSwapped(a,d){letc=0;leti=0;while(c<a.length){c+=swapSeries(a,i,d);i++;}}/** * Swaps elements in an array in-place. * * Variables: * a: array of numbers * i: index to start with * d: number of left-rotations to perform * c: count of numbers swapped, returned to loopUntilAllSwapped() * iS: index source (index of number to be moved) * iD: index destination (index iS will be moved to) * q: a queue that acts as a temporary buffer for numbers as they * move from source to destination * * Algorithm: * 1. Find index destination (iD) of a[iS] after d rotations to * left * 2. Place destination in temporary buffer (q). * 3. Replace destination with index source (iS) value (a[iS]). * 4. Repeat until we end where we started (iS === i) */functionswapSeries(a,i,d){letc=0;letiS=i;letq=[a[iS]];do{letiD=h(a.length,d,iS);q.push(a[iD]);a[iD]=q.shift();iS=iD;c++;}while(iS!==i);returnc;}/** * A constant-time formula to find index destination of i * after d rotations to left. */functionh(n,d,i){return((n-d%n)%n+i)%n;}
YOU don't need second vector for this. Just store the 0th index of a vector in some temp variable and when the whole array gets shifted by one left rotation ,store it at the n-1th index. Repeat the process till d becomes zero.
One drawback i can see here is that you are actually holding the IO operation while your code is getting executed. This will not affect for an input of 100, but think about an input of millions
Given an array of n integers and a number, d, perform d left rotations on the array.
So this means that the array is already given. Then we have to perform left rotation on that. Your solution may produce the required results, but as others have pointed out, I think that is not what has been asked in the solution. We have been given a complete array, and on that we have to perform the rotation.
Thank you! A small comment with regards the python implementation. For very large list of numbers there is a significant improvement in runtime if you create the new list using [0] times n (the length of arr) instead of a list comprehension.
your code is very small and still work fine,
will you explain me how [(i+n-d)%n] is working here. please
actually why you are using % here thats making me confuse
% (modulus) gives you the remainder of division.so 4%5=4,5%5=0 likewise 6%5=1, it helps you to stay inside the limit i.e lesser than the value n (i.e till n-1) eg:if n=5 it goes from 0 to 4.try this simple mod in calc or put it in a loop you will understand.we are getting the input value to the rotated index thats why (-d).if right rotation +d.
exactly...it's better to follow up with "Reversal algorithm". Follows O(n) time complexity without the usage of any temp storage. Hence saves storage and time both
At the very least, you would have to allocate memory to store one integer. The question then becomes what you consider to be important: memory, or run-time, or something in between. If your primary focus is memory, then your solution is just to move EVERYTHING in the array one unit over, multiplied by the number of iterations. (You can mitigate this somewhat by right-shifting if the number of iterations is more than 1/2 the size of the array.) If your focus is time, then just transfer everything to another array, and back again, giving ~ O(2n). A decent in-between (which is what I went with) is to move only the number of elements out that you need to move (max 1/2 n) to another array, shift everything else, then re-insert the moved elements.
The writeup specified that the output was to be printed the array reflecting the rotation. Nothing about having to actually create a rotated array and dump it to the console. And considering the submitter never supplied a stub to the actual rotation routine specifying the return as being an array, this is a legitmate answer. Likely not the one the OP intended.
If I were to give a coding test to someone I'd toss them something like this. Likely they'd code out a fancy in-place algorithm, in which I would warn them that they were over-engineering the solution for the specified output.
"A left rotation operation on an array of size n shifts each of the array's elements d unit to the left."
This isn't a correct solution. It's merely masking itself to be a solution. It's taking input and stuffing it pre-ordered into a new array. You should be doing a left rotation on an existing array.
Not sure what the n-d is to move outside the loop. Thanks for the feedback.
I'm trying to figure the site out to do a test for employment. I keep getting time out so I have been experimenting to see what is causing the times outs. I don't want to fail an employment related challenge b/c of a site timeout.
I find I have to write code that is less and less readable to try and get around the timeout issues.
your time complexity : O(n + n)
your space complexity : n
you can optimize it a little bit with :
time complexity : n + d
space complexity : d
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
int n = c.nextInt();
int d = c.nextInt();
int skipPart[] = new int[d];
int j =0;
for(int i = 0; i < n; i++) {
if(i >= d) {
System.out.print(c.nextInt() + " ");
} else {
skipPart[j] = c.nextInt();
j++;
}
}
for(int i = 0; i < skipPart.length; i++) {
System.out.print(skipPart[i] + " ");
}
}
Got it. I'm guessing being judged in a challenge your way of thinking is better -- do the challenge int he fewest steps possible. I really do not think of optimzing the stdin/stdout as they are just mechanism for giving you the data needed and demonstrating the algorithm is correct. I'm guessing if company is viewing my code, they will think with your mindset.
There are a lot of people solving the problem this way. Reread the problem statement and you'll see that this doesn't do what was asked. There only prints out the input in the order expected after a left rotation d times. The real problem is left rotating an existing array and then print the final content of the array. So what you need to do is read in your input and then store it into an unsorted, unrotated, etc array. Left shift that array, and then print it out from array[0] to array [n].
That's what I was thinking, too. The easiest solution to the expected output isn't necessarily solving the stated problem. But, that's also the nature of the problems. Perhaps a better problem would be one that simply passed in an array and you had to modify said array in place. That would at least ensure the right problem is being solved.
it is just awesome. I want to ask how you think this way, while everybody else is concentrating on different point, your solution is really different and cool :) My understanding is you approach the problem right at the beginning, the only issue is the coming up with this formula "(i+n-d)%n" good thinking akueisara39
intmain(){/* Enter your code here. Read input from STDIN. Print output to STDOUT */inti,d,k,n,temp,j;cin>>n;inta[n];for(i=0;i<n;i++)cin>>a[i];cin>>d;for(i=0;i<n;i++)cout<<" "<<a[(i+(n-d))%n];return0;}
It can be optimized in terms of space if you don't store the whole array, but only the rotated elements. If the elements are 1 2 3 ... 100000, and the number of left rotations is 2, you can save the first two elements (1 and 2) and directly print the rest as soon as you read them. Finally, print the saved ones. The difference in space is from 100000 ints to 2 ints.
no no, if you have 1000 rotations in an array of 30, you have 1000/30 complete rotations (rotations of the whole array) and 1000%30 effective left rotations. So you store only the first 1000%30 elements. Sorry for the initial incomplete explanation, my fault.
How come you reached to this logic array[(i+n-d)%n], i understood what you did here but, having hard time to understand how did you get to this formula, does it comes with expreince or some mathematical practice i am lacking.
Thanks
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] array = new int[n];
int c=0,i,temp;
for(i=0; i
I was thining on the same lines after I got the timeout error. But didn't reach anywhere, I was still using the same number of For loops some how! Thanks a lot!
suppose if i enter value of n=5;d=2;
then it will accept five numbers not more than that but if i wil not hit the Enter key then it will have been accepting the many values i will hav to take only 5 values not more than that
¿This works for you? In my analysis, this does a right rotation instead of a left rotation. Isn't it? You should implement the logic for translate right to left rotations or to invert the direction.
Hi akueisara39 : i appreciate your code as it appears to be out of box solution . but i feel it throws an exception when the number of shift operations is greater than the size(d>n) of the array so just added few lines of code to it .
int[] array = new int[n];
if(d>n) d=d%n;
for(int i=0; i
array[(i+n-d)%n] = scan.nextInt();
}
Here's my solution in Kotlin. I did it using circular LinkedList.
data class Node(val value: Int, var nextNode: Node?)
fun main(args: Array) {
val (n, d) = readLine()!!.split(" ").map(String::toInt)
val list = readLine()!!.split(" ").map(String::toInt)
var head = Node(list[0], null)
var current = head
var rotatedHead = head
for (i in 1 until n) {
val node = Node(list[i], null)
current.nextNode = node
current = node
if (i == d % n)
rotatedHead = node
}
current.nextNode = head
current = rotatedHead
repeat(n) {
print(current.value.toString() + " ")
current = current.nextNode!!
}
I liked your approach.But I would like to pin point one thing here as you have been already given an array and N number of rotation.ON that array you have to perform operations.You are changing it while reading from console.
please have a look at this and let me know if this can be optimized.
static int[] leftRotation(int[] a, int d) {
// Complete this function
int[] b= new int[a.length];
for(int iLoop=0;iLoop<a.length;iLoop++){
b[iLoop]=a[iLoop];
}
for(int iLoop=0;iLoop<a.length;iLoop++){
a[iLoop]=b[(iLoop+d)%a.length];
}
return a;
}
But Really good solution though.
hey, your logic is cool . but i dont understand it . like i am not able to figure out how it works (in the logical sense ) . why do you add n in(i+n-d)? It would be really nice if you explain . thank you
Just calculate the effective number of rotations d % n and then simply change the list accordingly. Simple Pythonic solution with O(1) complexity:
def rotate(a, r):
l = a[r:] + a[:r]
return l
if __name__ == '__main__':
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().rstrip().split()))
r = d % n
print(*rotate(a,r))
def rotation(a):
l=a[::-1]
for i in range(d):
r=l.pop()
l.insert(0,r)
return(l[::-1])
Hy my logic is corrct I have checked it in python compiler using custom input but i am unable to return the output in hackerrank compiler. help me out here
I had a similar approach. Mine is slower but doesnt use extra memory. Question: Your solution duplicates the memory since L is another list the same size of a ?
def rotateLeft(n ,d , a):
i = 0
while i < (d % n):
a.append(a.pop(0))
i += 1
print(*a)
If rotation is greater than the length of the string, this line gets used. Say we have 5 as the length of the string. If the rotation given as 7, it is actually 2 and hence 7%5 == 2. If you're still unsure, try the above scenario and see how this line helps :)
If "d" is greater than "n" , for example take n=5 and d = 10
let me take arr[5] = {1,2,3,4,5}
for 10 rotations ans should be same right but it does not work!!!
5 10
1 2 3 4 5
ans : 1 1878011968 1329038170 32 16.
so this method does not work for the case where the number of rotation is larger than array size!!!
instead of (i+n-d)%n i think we can use d%n if we limit i from d to n+d instead of 0 to n, working will be exactly same but understanding the code will become easier
I know I'm ressurecting this old comment at this point, but if I'm not mistaken (and I very well could be), this method seems to break if the number of rotations, d, exceeds the number of n integers in the array?
I liked your approach, and I was recreating it in JS when I saw this possible issue.
publicstaticList<Integer>rotateLeft(intd,List<Integer>arr){// Write your code hereList<Integer>lRotate=newArrayList<>(arr);Integersizes=lRotate.size()-1;for(inti=0;i<d;d--){Integerhold=lRotate.remove(0);lRotate.add(sizes,hold);}returnlRotate;}}
publicstaticList<Integer>rotateLeft(intd,List<Integer>arr){// Write your code hereList<Integer>lRotate=newArrayList<>(arr);Integersizes=lRotate.size()-1;for(inti=0;i<d;d--){Integerhold=lRotate.remove(0);lRotate.add(sizes,hold);}returnlRotate;}}
It is not satisfying the test case but in system it it running...
5 2 //n=5, d=2
1 2 3 4 5 //array
3rd iteration-
i=2
array(i+n-d)%n=scan.nextInt();
array(2+5-2)%5=0
but it is printing index 5....
My Js solution
function rotateLeft(d, arr) {
// Write your code here
d=d%arr.length;
let arr_to_rotate=arr.splice(0,d);
arr= arr.concat(arr_to_rotate);
return arr;
}
Left Rotation
You are viewing a single comment's thread. Return to all comments →
This is my solution in Java
can i get an explanation,pls?
Each time I read an element of the array from the input, I directly assign it to the array at the speific index after shifting. d left rotations equal (n-d) right rotations. The array has a size of n, so when the index (i+n-d) is equal to n, the index actually goes back to the starting index. I use mod to get the correct index where I want to assign the element when the index is larger than n. I'm not an english native speaker. Hope you will understand what I explain. :)
thank you so much.very helpful.
This is Great
My extremely simple solution. Easy to understand.
Hackerrank - Arrays: Left Rotation Solution
I see a problem here. You've assumed that we can sort the array at the time of initialization itself. Though it's good, but IMHO, the real test is to sort an already existing array with space constraints.
Good thinking! I guess it could be handled with another array logically. My two cents.
I like you code some much.PLEASE can you add some explainatioin.I will be very glad
It just generates an array first from Stdin, then illustrates the way to left-rotate an EXISTING array.
I'm failing to see where it actually does a left rotate of an existing array.
What I'm seeing is (from assumption of ...) array[0..n] is empty initially. getArray[0..n] stores input from stdin. store rotated result into array[0..n].
The existing array is getArray. That array is still in an unrotated order. The array[0..n] isn't considered the exiting array as it is empty.
Challenge to you: get rid of getArray array and store input into array[] array. Rotate that array and then print the end result of that array.
This code is actually quite efficient. So for the following values, n=5 (number of elements in the array), d=2 (number of rotations)and assuming i goes from 0-4. (i + n - d)%n with the iteration of i from 0-4: (0+5-2)%5=3 (1+5-2)%5=4 . . . (4+5-2)%5=2 So essentially, you are changing the locations of the elements in the array. How the "%" works is that it takes the remainder. So for example, 1%7=1 since 1 cannot be divided by 7 which means 1 is the remainder.
that's great, can you provide any mathematical illustration to arrive (i+n-d)%n ?
Great, How did you think of (i+n-d)%n?
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.
Have you tried running this? You actually run into an issue where you just propagate the first value in the array across all other indices in the array using your method.
The second for loop moves the value at index 0, the 1, over to index 1, overwriting the value 2 at index 1, and then this 1 gets written into all the other indices as a result.
Solid answer. I would like to point out to people that this does require double the memory of the intial answer as this requires a second array to store all the properly ordered array. If you're on a memory tight situation, this would not be a favorable solution.
To solve this, I've shifted the elements in the array in O(n) time and O(n) memory (vs O(2n)). Not as easy on the eyes, though :(
I'm ignoring the processing time on input string manipulation and such. This examples assumes they gave us an existing array to manipulate.
Hey! Could you include comments in your code please? I use C and dont kow other language as of now but would like to learn from your solution O(n) is preety nice
i think your solutions is O(n^2) for the worst case.
It looks like it, because of the nested loops. But it'll break out of all loops after
n
loops.Hey could you help me confirm if the time complexity of my code is a constant?
As all line are executed once the time complexity is constant O(1).
If it was right rotation, what would u edit in this code??
Excellent!
Solution.cpp:1:1: error: ‘function’ does not name a type; did you mean ‘union’? function processData(input) { ^~~~~~~~ union Solution.cpp:45:1: error: ‘function’ does not name a type; did you mean ‘union’? function shiftLeft(n, d, i) { ^~~~~~~~ union
Revisited this with an easier-on-the-eyes solution that finishes in O(n) time with O(n) memory.
YOU don't need second vector for this. Just store the 0th index of a vector in some temp variable and when the whole array gets shifted by one left rotation ,store it at the n-1th index. Repeat the process till d becomes zero.
I did this with python but they are saying try a more optimized solution
In my opinion, the 3rd for-loop is unnecessary.. Instead it should be merged with the 2nd one.
This should be called circle array,haha
Doesn't this use extra space?
for me is: (d + i) % n
what does it mean...????
%.....?
It means to divide the numbers and return the remainder
One drawback i can see here is that you are actually holding the IO operation while your code is getting executed. This will not affect for an input of 100, but think about an input of millions
nice!! different way of thinking! you cahnged the way of thinging..
getArray[i] = scan.next(); this is an error.It cannot be converted into string.
getArray[i] = scan.nextInt(); this is correct statement.
Hey @qianyonan
You have forgot to initialize the empty array i.e. array variable .
that's why little bit hard to understand to newbie.
One more thing , Don't you think you are using extra space bcz you can solve this problem using existing array too.
using 2 arrays?
space complexity is O(n)
Very nice. I didn't even think to assign the integers to their "new" positions in the array as they are read in.
Perhaps this one is any good:-
Concise code and Wonderful explanation.This should go to Editorial.
why can't we do the left rotation. like you said d left rotation is equal to n-d right rotation.what is problem in that...
Given an array of n integers and a number, d, perform d left rotations on the array. So this means that the array is already given. Then we have to perform left rotation on that. Your solution may produce the required results, but as others have pointed out, I think that is not what has been asked in the solution. We have been given a complete array, and on that we have to perform the rotation.
thanks
very convenient solution
pretty rad :),loved it.
Thanks a lot ! Really helpful !
Wow probably the best solution of this question...Thanks a lot :)
thanks so much for your great logic
thank you so much.... The approach was great.
Thanks
Brilliant..Simply Brilliant
This is great.
thanks :)
appriciatable work done by you ;) ^_^
what if i had a hard code list
here is problem solution in java python c++ c and javascript programming. https://programs.programmingoneonone.com/2021/05/hackerrank-left-rotation-solution.html
Thank you! A small comment with regards the python implementation. For very large list of numbers there is a significant improvement in runtime if you create the new list using [0] times n (the length of arr) instead of a list comprehension.
thanks mate
Here is my solution for this problem(java,javascript)
https://webdev99.com/left-rotationproblem-solving-data-structures/
for detailed solution checkout above article
javascript:
Java:
new python easy solution https://hacker-rank-dsa-python.blogspot.com/2022/03/left-rotation.html
Can u explain me the Java code once?
Hi @webdev99
In js solution you given, what if d is larger than length ?
your code is very small and still work fine, will you explain me how [(i+n-d)%n] is working here. please actually why you are using % here thats making me confuse
% (modulus) gives you the remainder of division.so 4%5=4,5%5=0 likewise 6%5=1, it helps you to stay inside the limit i.e lesser than the value n (i.e till n-1) eg:if n=5 it goes from 0 to 4.try this simple mod in calc or put it in a loop you will understand.we are getting the input value to the rotated index thats why (-d).if right rotation +d.
It's a great solution but how would someone come up with the idea to use a modulus in this case?
when ever you see in problem that a cycle is form. try modulus aproach
My extremely simple solution.
Hackerrank - Arrays: Left Rotation Solution
How is 4%5 = 5?
if % is not given the value of (n+i-d) may exceed the array length so after % operator the value lies in the range of array length
Here is my solution for this problem(java,javascript)
https://webdev99.com/left-rotationproblem-solving-data-structures/
for detailed solution checkout above article
javascript:
Java:
This is my C# sharp code.
THANK YOU SO MUCH FOR THIS SOLUTION!!!!!!!!!!!!!!!!!!!! :')
I've been searching for both right & left shift formulae!!!
This code will fail the test. This is the fix:
for (int i = 0; i < n; i++) { Console.Write(array[i]+" "); }
Console.WriteLine();
Very slow. & it will not work out 1,000,000,000 records
exactly...it's better to follow up with "Reversal algorithm". Follows O(n) time complexity without the usage of any temp storage. Hence saves storage and time both
Not the desired approach but it gets the job done though
static void Main(String[] args) { string[] token=Console.ReadLine().Split(' '); int n=Convert.ToInt32(token[0]); int k=Convert.ToInt32(token[1]); string[] arr1=Console.ReadLine().Split(' '); int [] arr=Array.ConvertAll(arr1,int.Parse);
Great solution ajaycarnet. I compared yours with my own and yours is much faster.
My C# code:
I have submit my code but last two case didnt pass because of execution time.I couldnt think assign variable before calling the method.Thank you
Did anyone consider if we cant alloc a new array to store sorted array, only operate the old array to left rotation?
At the very least, you would have to allocate memory to store one integer. The question then becomes what you consider to be important: memory, or run-time, or something in between. If your primary focus is memory, then your solution is just to move EVERYTHING in the array one unit over, multiplied by the number of iterations. (You can mitigate this somewhat by right-shifting if the number of iterations is more than 1/2 the size of the array.) If your focus is time, then just transfer everything to another array, and back again, giving ~ O(2n). A decent in-between (which is what I went with) is to move only the number of elements out that you need to move (max 1/2 n) to another array, shift everything else, then re-insert the moved elements.
It is not the best solution but it requires only one array:
Yes. But I think it will slower than
Correct me if I am wrong.
My in-place O(n) solution. No allocation required
Why has everyone ignored this?
Is it possible to do the same in C# using only one array (as one array must hold the splitted values and other to place them accordingly) ?
It is not the best solution but it requires only one array:
This does the rotation in place. 1 line solution.
for (int i = d; i < d + n; i++) Console.Write($"{a[i%n]} ");
The writeup specified that the output was to be printed the array reflecting the rotation. Nothing about having to actually create a rotated array and dump it to the console. And considering the submitter never supplied a stub to the actual rotation routine specifying the return as being an array, this is a legitmate answer. Likely not the one the OP intended.
If I were to give a coding test to someone I'd toss them something like this. Likely they'd code out a fancy in-place algorithm, in which I would warn them that they were over-engineering the solution for the specified output.
厉害,佩服
Thumbs up, for sharp thinking. Complicated my solution before stumbling on the same short solution myself :D
"A left rotation operation on an array of size n shifts each of the array's elements d unit to the left."
This isn't a correct solution. It's merely masking itself to be a solution. It's taking input and stuffing it pre-ordered into a new array. You should be doing a left rotation on an existing array.
move that n-d outside the loop its always same. other then that your solution is best.
Not sure what the n-d is to move outside the loop. Thanks for the feedback.
I'm trying to figure the site out to do a test for employment. I keep getting time out so I have been experimenting to see what is causing the times outs. I don't want to fail an employment related challenge b/c of a site timeout.
I find I have to write code that is less and less readable to try and get around the timeout issues.
your time complexity : O(n + n) your space complexity : n
you can optimize it a little bit with :
time complexity : n + d space complexity : d
public static void main(String[] args) { Scanner c = new Scanner(System.in); int n = c.nextInt(); int d = c.nextInt(); int skipPart[] = new int[d]; int j =0; for(int i = 0; i < n; i++) { if(i >= d) { System.out.print(c.nextInt() + " "); } else { skipPart[j] = c.nextInt(); j++; } } for(int i = 0; i < skipPart.length; i++) { System.out.print(skipPart[i] + " "); } }
Got it. I'm guessing being judged in a challenge your way of thinking is better -- do the challenge int he fewest steps possible. I really do not think of optimzing the stdin/stdout as they are just mechanism for giving you the data needed and demonstrating the algorithm is correct. I'm guessing if company is viewing my code, they will think with your mindset.
There are a lot of people solving the problem this way. Reread the problem statement and you'll see that this doesn't do what was asked. There only prints out the input in the order expected after a left rotation d times. The real problem is left rotating an existing array and then print the final content of the array. So what you need to do is read in your input and then store it into an unsorted, unrotated, etc array. Left shift that array, and then print it out from array[0] to array [n].
thanks. Got it.
That's what I was thinking, too. The easiest solution to the expected output isn't necessarily solving the stated problem. But, that's also the nature of the problems. Perhaps a better problem would be one that simply passed in an array and you had to modify said array in place. That would at least ensure the right problem is being solved.
I like this I wish I'd came to this algorithm myself ...
Similarly:
Great Solution!
b=a[d : ]
b.append(a[:d])
print(*b)
A really good solution. I was unable to figure it out mathematically XD.
very clever, thanks!
What a great hack, akueisara39! Given that the defaulted code that read the elements into an array, I saw myself forced to use additional space.
Can someone explain how you came about the formula (i+n-d)? I am not able to understand how that formula is derived?
good logic akueisara. i used similar logic like "(i+n-d)%n" in circular linked list.
it is just awesome. I want to ask how you think this way, while everybody else is concentrating on different point, your solution is really different and cool :) My understanding is you approach the problem right at the beginning, the only issue is the coming up with this formula "(i+n-d)%n" good thinking akueisara39
It is a greate solution.
I think something similar, but your solution is better.
pls let me knw wats wrng in this?
cin >> d; should be after cin >> n;
you need to use vector instead of array for memory allocation at runtime else if you are using array they you have to use dynamic array.
vector leftRotation(vector a, int d) { int temp; for(int j=0;j
//whats wrong one test case not working(timeout error)
write a[(i+d)%n] in place of a[(i + (n - d)) % n]
My C solution was similar:
Hand down! Best solution for me!
Nailed it!
It can be optimized in terms of space if you don't store the whole array, but only the rotated elements. If the elements are 1 2 3 ... 100000, and the number of left rotations is 2, you can save the first two elements (1 and 2) and directly print the rest as soon as you read them. Finally, print the saved ones. The difference in space is from 100000 ints to 2 ints.
what if I have thousand rotation??then I have to store thousands of int?
no no, if you have 1000 rotations in an array of 30, you have 1000/30 complete rotations (rotations of the whole array) and 1000%30 effective left rotations. So you store only the first 1000%30 elements. Sorry for the initial incomplete explanation, my fault.
appreciated!!bt still don't you think it will require alot memory??even if u will use 1000%30
I think on the place to store those elements it will b more efficient to jst show those elements.
How come you reached to this logic array[(i+n-d)%n], i understood what you did here but, having hard time to understand how did you get to this formula, does it comes with expreince or some mathematical practice i am lacking. Thanks
Pure Magic !!!
The logic does it in one loop. Brilliant.
Very creative solution!
3 errors is generating
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int[] array = new int[n]; int c=0,i,temp; for(i=0; i
} }
I used the same logic but timeout error is coming for the last case.
what is the issue if i write this way.
Awesome , this really saves time .Thank You..!!
I was thining on the same lines after I got the timeout error. But didn't reach anywhere, I was still using the same number of For loops some how! Thanks a lot!
So without using an extra array u did it. Basically u dont have an input array.. Great
is the array[(i+n-d)%n] is some standard algo?
suppose if i enter value of n=5;d=2; then it will accept five numbers not more than that but if i wil not hit the Enter key then it will have been accepting the many values i will hav to take only 5 values not more than that
Awesome...
amazing!!
¿This works for you? In my analysis, this does a right rotation instead of a left rotation. Isn't it? You should implement the logic for translate right to left rotations or to invert the direction.
Nice
Hi akueisara39 : i appreciate your code as it appears to be out of box solution . but i feel it throws an exception when the number of shift operations is greater than the size(d>n) of the array so just added few lines of code to it .
int[] array = new int[n]; if(d>n) d=d%n; for(int i=0; i array[(i+n-d)%n] = scan.nextInt();
}
Instead of rotating each element we can just cut the string upto that index and paste(append) it at the end of the string.
A solution for python would be
beautiful solution!!!
but this will not work when d > len(a)
Correct, I added this line first to account for cases when d > len(a).
You don't need the if statement here. It's the same as writing: d = d % a
true, but the constraints say 1 <= d <= n :)
It will not work it if it is d > = len(a)
Here's my solution in Kotlin. I did it using circular LinkedList. data class Node(val value: Int, var nextNode: Node?)
fun main(args: Array) { val (n, d) = readLine()!!.split(" ").map(String::toInt) val list = readLine()!!.split(" ").map(String::toInt) var head = Node(list[0], null) var current = head var rotatedHead = head for (i in 1 until n) { val node = Node(list[i], null) current.nextNode = node current = node if (i == d % n) rotatedHead = node } current.nextNode = head
}
genius!
I liked your approach.But I would like to pin point one thing here as you have been already given an array and N number of rotation.ON that array you have to perform operations.You are changing it while reading from console. please have a look at this and let me know if this can be optimized.
static int[] leftRotation(int[] a, int d) { // Complete this function
how did you do that it is amazing...how can you think like that.....
nice explanation genius
Brilliant
very cool way of doing!
Your approach to this problem was great and one correction if d > n then in those cases you should recompute d as d = d%n;
cool! i mean hats off
If the number of rotations is greater than the number of elements, than this can still throw an IndexOutOfBounds as (i+n-d) is negative.
To solve this one can use a true modulus function like Math.floorMod(i-d, n) which rather than returning the remainder returns a modulus. https://stackoverflow.com/questions/5385024/mod-in-java-produces-negative-numbers
Yes this code is useful.
wow bro you are great
How did you come up with this idea? I was puzzled with this task for two days and still didn't succeed in it...
hey, your logic is cool . but i dont understand it . like i am not able to figure out how it works (in the logical sense ) . why do you add n in(i+n-d)? It would be really nice if you explain . thank you
what a piece of outstanding code........well done
Nice....
Just calculate the effective number of rotations d % n and then simply change the list accordingly. Simple Pythonic solution with O(1) complexity:
why did you add '*' in print(*rotate(a,r))????
'*' here is unpacking the items of the list that is returned from rotate method.
def rotation(a): l=a[::-1] for i in range(d): r=l.pop() l.insert(0,r) return(l[::-1])
I had a similar approach. Mine is slower but doesnt use extra memory. Question: Your solution duplicates the memory since L is another list the same size of a ?
you can do it without another list here is the solution...
if name == 'main': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) r = d % n print(*(a[r:]+a[:r]))
Nice concise code. One question: as d%n is returning d only in every test case so why not use d here instead of d%n.
I have used d in the loop and it worked every time.
Am I missing something here?
If rotation is greater than the length of the string, this line gets used. Say we have 5 as the length of the string. If the rotation given as 7, it is actually 2 and hence 7%5 == 2. If you're still unsure, try the above scenario and see how this line helps :)
Thank you, GOOD EXPLANATION
I have coded the same logic in c++ and I am getting a segmentation fault.
If you're looking for something more easy to understand:
Another method for those who are concerned about manipulating existing array:
Good job, bro!
Why not to use Collections.rotate()
Amazing
wow.. super,What a logic... nice###:)
It will not work out if d>n.
came to the comments for the lulz was impressed instead! thats a very clever way of doing it
i know bro but i am not getting placed in any of the companies :(
shit not working for u?
no man
Great solution. Congratulations.
this works only when d<=n/2.
If "d" is greater than "n" , for example take n=5 and d = 10 let me take arr[5] = {1,2,3,4,5} for 10 rotations ans should be same right but it does not work!!! 5 10 1 2 3 4 5 ans : 1 1878011968 1329038170 32 16.
so this method does not work for the case where the number of rotation is larger than array size!!!
error: expected unqualified-id before ‘public’ public class Solution { ^~~~~~
We can optimize the space complexity in the following way:
O(n)
O(1)
Approach:
Code:
great.... i did this but my time complexity was high...
this logic is lit like what was your approach?? how did you found out (i+n-d)%n??
It is perfect thankyou for sharing this but i just want to know how you came to think that it is i+n-d%n ?
Hey can you teach me how to get this logic --> (i+n-d) can you tell me how to approach for solution like this. @akueisara39
python3 for newbie solution
for _ in range(d):
Popping the first element in a python list is O(n) which will become very slow when the size of the list is very large.
Learn more about time complexity
You should use deque when doing such.
In deque, pop to remove last item O(1) popleft to remove first item O(1)
awesome trick
awesome....idk why I can't think like this
how did you comeup with this... this is mind blowing. how you did the math here.
brilliant
instead of (i+n-d)%n i think we can use d%n if we limit i from d to n+d instead of 0 to n, working will be exactly same but understanding the code will become easier
Python 3 solution
I'm new to hackerrank and getting a warm glow seeing how much brainpower is required for Java / C# solutions etc. compared with Python:
O(n):
`def rotateLeft(d, arr):
I know I'm ressurecting this old comment at this point, but if I'm not mistaken (and I very well could be), this method seems to break if the number of rotations, d, exceeds the number of n integers in the array?
I liked your approach, and I was recreating it in JS when I saw this possible issue.
thanks for comment but if 'd' exceeds 'n' or not for safer side we can use d=d%n
My solution in C++
My code in C++
This is my solution in java
its very similar to using circular linked list
It is not satisfying the test case but in system it it running... 5 2 //n=5, d=2 1 2 3 4 5 //array 3rd iteration- i=2 array(i+n-d)%n=scan.nextInt(); array(2+5-2)%5=0 but it is printing index 5....
Here is my solution for this problem(java,javascript)
https://webdev99.com/left-rotationproblem-solving-data-structures/
for detailed solution checkout above article
javascript:
Java:
Do it works for given array ? Its fine if we are filling up array via scanner.
vector rotateLeft (int d, vector arr) {
int n=arr.size();
vector result;
result.insert( result.begin(), arr.begin()+d,arr.begin()+n);
vector result_2;
result_2.insert(result_2.begin(),arr.begin(),arr.begin()+d);
result.insert(result.end(),result_2.begin(),result_2.end());
return result;
}
My Js solution function rotateLeft(d, arr) { // Write your code here d=d%arr.length; let arr_to_rotate=arr.splice(0,d); arr= arr.concat(arr_to_rotate); return arr; }
you had done it in one step ,😍
:)