HackerRank Arrays: Left Rotation

Given a collection of integers and the left shift we want to apply to it, return a collection in the new configuration.

This is the first HackerRank problem in their Cracking the Coding Interview series.

Python solution is trivial, nevertheless I converted their sample to a test case:
def test_provided_1(self):
    self.assertEqual([5, 1, 2, 3, 4], solution([1, 2, 3, 4, 5], 5, 4))
Given a list, its length, and the required left shift. The result should be the left-shifted input list.

This is a one-liner solution:
def solution(values, size, shift):
    return values[shift:] + values[:shift]
Obviously the second parameter is not needed, I left it there as for problem requirement.

I ask Python to slice a first time the passed list starting from shift to the end, then a second time, from beginning to shift (remember that the interval is close to the left and open to the right), and finally join them.

I have spent more time setting up the repository on GitHub and the project than solving the problem itself. So, even if I don't think it adds much value, here is the link to the test case and the python script in there.

No comments:

Post a Comment