Skip to content

Commit acfac7b

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 17.8 MB (85.60%)
1 parent 8ef979e commit acfac7b

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<p>Given the <code>head</code> of a linked&nbsp;list, rotate the list to the right by <code>k</code> places.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" style="width: 450px; height: 191px;" />
6+
<pre>
7+
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
8+
<strong>Output:</strong> [4,5,1,2,3]
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" style="width: 305px; height: 350px;" />
13+
<pre>
14+
<strong>Input:</strong> head = [0,1,2], k = 4
15+
<strong>Output:</strong> [2,0,1]
16+
</pre>
17+
18+
<p>&nbsp;</p>
19+
<p><strong>Constraints:</strong></p>
20+
21+
<ul>
22+
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
23+
<li><code>-100 &lt;= Node.val &lt;= 100</code></li>
24+
<li><code>0 &lt;= k &lt;= 2 * 10<sup>9</sup></code></li>
25+
</ul>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
8+
if head is None or head.next is None:
9+
return head
10+
11+
current, n = head, 0
12+
while current:
13+
n += 1
14+
current = current.next
15+
16+
k %= n
17+
if k == 0:
18+
return head
19+
20+
fast = slow = head
21+
for _ in range(k):
22+
fast = fast.next
23+
while fast.next:
24+
fast, slow = fast.next, slow.next
25+
26+
result = slow.next
27+
slow.next = None
28+
fast.next = head
29+
return result

0 commit comments

Comments
 (0)