Menu

Post image 1
Post image 2
Post image 3
Post image 4
Post image 5
1 / 5
0

61. Rotate List

DEV Community·MD ARIFUL HAQUE·27 days ago
#FvIpELdn
Reading 0:00
15s threshold

61. Rotate List Difficulty: Medium Topics: Linked List , Two Pointers Given the head of a linked list, rotate the list to the right by k places. Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] Example 2: Input: head = [0,1,2], k = 4 Output: [2,0,1] Example 3: Input: head = [1], k = 0 Output: [1] Example 4: Input: head = [1,2,3], k = 0 Output: [1,2,3] Example 5: Input: head = [], k = 5 Output: [] Example 6: Input: head = [1,2,3], k = 5 Output: [2,3,1] Constraints: The number of nodes in the list is in the range [0, 500] . -100 <= Node.val <= 100 0 <= k <= 2 * 10⁹ Solution: This solution rotates a singly linked list to the right by k places in O(n) time and O(1) space. It first computes the list length, reduces k modulo the length, finds the new head and tail, then performs the rotation by linking the tail to the old head and breaking the list at the new tail. Approach: Find list length and tail node to handle cases where k is larger than the list length.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More