I am trying to solve problem 189 on leetcode
The question is:
Given an array, rotate the array to the right by k steps, where k is non-negative.
According to the solution, I have tried out to implement the idea given in approach 2: by using an "extra" array. Still, I am unable to get the desired result. What's the issue with this code?
I tried brute force approach as well but it's not accepted there, so trying this!! Any help would be appreciated!
i = 0
l = len(nums)
arr = [0]*l
while i < len(nums):
split = l-k
if i >=0 and i < split:
arr[i+k] = nums[i]
if i >= k+1 and i < l:
arr[i-k-1] = nums[i]
i+=1
nums = [0]*l
for a in range(0,l):
nums[a] = arr[a]
print(arr)
print(nums)
After getting some help, I tried with the slicing approach(as suggested in the comments) and this is the code I could come up with:
l = len(nums)
a = nums[:l-k] # appending part
nums = nums[l-k:] # real array
for i in a:
nums.append(i)
print(nums)
Still, this is not running on that website. I am getting the correct output array but not exactly what's the requirement.