-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFB_Rotates_List_By_K_Elements
More file actions
65 lines (57 loc) · 1.76 KB
/
FB_Rotates_List_By_K_Elements
File metadata and controls
65 lines (57 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
This problem was asked by Facebook.
Write a function that rotates a list by k elements.
For example, [1, 2, 3, 4, 5, 6] rotated by two becomes [3, 4, 5, 6, 1, 2].
Try solving this without creating a copy of the list.
How many swap or move operations do you need?
# with example we r doing left rotate here
# ways to rotate a list in python by slicing,list comprehension & , numpy.roll() function,collections.deque.rotate()
# Solution by slicing
def rotate(seq, k):
return seq[k:] + seq[:k]
if __name__ == '__main__':
nums = list(range(1,7))
k = 2
x = rotate(nums, k)
print(x) # [3, 4, 5, 6,1, 2]
#Note: Slicing lists does not generate copies of the objects in the list; it just copies the references to them.
# Solution By List Comprehension
class Solution:
def rotate(self, nums, k):
return [nums[(i + k) % len(nums)] for i, x in enumerate(nums)]
sol=Solution()
nums = list(range(1,7))
k = 2
fx_rot=sol.rotate(nums, k)
print(fx_rot)
# Solution By deque.rotate()
from collections import deque
class Solution:
def rotate(self, nums, k):
d = deque(nums)
d.rotate(-k)
nums[:] = list(d)
return nums
sol=Solution()
nums = list(range(1,7))
k = 2
fx_rot=sol.rotate(nums, k)
print(fx_rot)
#Solution By Brute force
class Solution:
def rotate(self, nums, k):
def numReverse(start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
k, n = k % len(nums), len(nums)
if k:
numReverse(0, n - 1)
numReverse(0, k - 1)
numReverse(k, n - 1)
return nums
sol=Solution()
nums = list(range(1,7))
k = -2
fx_rot=sol.rotate(nums, k)
print(fx_rot)