-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateList_Day48.py
More file actions
68 lines (53 loc) · 1.36 KB
/
Copy pathRotateList_Day48.py
File metadata and controls
68 lines (53 loc) · 1.36 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
66
67
#Brute Approach
class Solution:
def rotateRight(self, head, k):
if not head or not head.next or k == 0:
return head
# Get length
length = 0
curr = head
while curr:
length += 1
curr = curr.next
k = k % length
if k == 0:
return head
# Rotate k times
for _ in range(k):
prev = None
curr = head
while curr.next:
prev = curr
curr = curr.next
prev.next = None
curr.next = head
head = curr
return head
# TC - O(k * n)
# SC - O(1)
#Optimal Approach
class Solution:
def rotateRight(self, head, k):
if not head or not head.next or k == 0:
return head
# Find length and tail
length = 1
tail = head
while tail.next:
tail = tail.next
length += 1
k = k % length
if k == 0:
return head
# Make it a circular list
tail.next = head
# Find new tail at (length - k) steps
steps_to_new_tail = length - k
new_tail = head
for _ in range(steps_to_new_tail - 1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_head
# TC - O(n)
# SC - O(1)