Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

​

Problem Challenge 2: Rotate a LinkedList (medium)

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 2 years ago

#class Node: # def __init__(self, value, next=None): # self.val = value # self.next = next class Solution: def rotate(self, head, rotations): if rotations == 0: return head # get length of linked list and get necessary rotation length = 0 current, previous = head, None while current: length += 1 current = current.next remainder = rotations % length if remainder == 0: return head newHeadIndex = length - remainder current = head i = 0 newHead = None while current: next = current.next # find and break the link before newHeadNode if i == newHeadIndex - 1: current.next = None # store new head node elif i == newHeadIndex: newHead = curre
A

Anonymous

· 2 years ago

#class Node: # def __init__(self, value, next=None): # self.val = value # self.next = next class Solution: def rotate(self, head, rotations): def get_moves(): length = 0 node = head while node: node = node.next length += 1 remain = length - (rotations % length) return remain # get the number of moves moves = get_moves() # move the nodes based on the number of moves count = 1 node = head while count < moves: count += 1 node = node.next # cut the linkedlist to 2 parts next_part = node.next node.next = None # move to the end of the second part node = next_part while node and node.next: node = node.next # link the 2 parts again if node:
A

Anonymous

· 4 years ago

Here is what I came up with! O(N) and a bit more readable IMO. Fire away! Image

Reading Progress

0%


Vote for new content