This is a straightforward O(n) solution.
Slice(), push() and all that are nice.. but won't a for loop do better in this case? (to avoid allocation issues)
Well, your proposed solution only shifts the elements one place, while the challenge was to create a function that shifts them an undetermined number of places.
Nothing wrong, it just wasn't on top of my head when I first approached the problem, especially applying the modulo operator, which was not an obvious/natural thought process for me. And somehow I didn't find that solution during my search. So thanks so much for sharing. Adding to my notes as we speak :)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
What's wrong with the obvious solution:
This is a straightforward O(n) solution.
Slice(), push() and all that are nice.. but won't a for loop do better in this case? (to avoid allocation issues)
Well, your proposed solution only shifts the elements one place, while the challenge was to create a function that shifts them an undetermined number of places.
just change:
let next = (i+1) % a.length
to
let next = (i+offset) % a.length
Where offset is the number of spaces you want to shift.
Your algorithm works for only 1 place shift, even with the edit you provided.
Nothing wrong, it just wasn't on top of my head when I first approached the problem, especially applying the modulo operator, which was not an obvious/natural thought process for me. And somehow I didn't find that solution during my search. So thanks so much for sharing. Adding to my notes as we speak :)