Skip to main content

1721 - Swapping Nodes in a Linked List.

Hi, Today we will be solving leetcode qs 1721 - Swapping Nodes in a Linked List.

This qs is really simple. We need to swap the nodes placed at k distance from the start and end of the Linked List. So let's suppose you have a Linked List input as follows:

1 -> 2-> 4 -> 5 -> 7 -> 8 -> 10-> 9

 and you are given a k = 2, so the output should be

1 -> 10-> 4 -> 5 -> 7 -> 8 ->2 -> 9

so how do we achieve it???

Intuition

The most brute force solution one can think of is using Array data structure. For that, we will traverse through linked List and store all the elements in the Array, swap the two numbers and again insert it in theLinked List again. Not bad, but let's deal with it, it is not the optimal solution and far from being as an acceptable solution in interviews.

So what can we done instead of that???

Let's try to look deep into the working of Linked List first and how do we traverse it. Linked List is a linear data structure that consists of a value and a next pointer.

This is how we initiate a LinkedList Node:


class LinkedList:
def __init__(self, val):
self.val = val
self.next = None


Here val is the value stored in Linked List and next is the pointer that is used to point to next Node. Currently it is pointing to None.

So in general to access the Linked List Nodes we use pointers. The first node in the linked list is defined as the head and last element is defined as tail. The tail nodes points to None defining that Linked List has ended.

So coming back to the qs, We know that we will be using pointers, here as we need two values kth value from start and end ,  we will be using concept of two pointers

Approach

We will make sure to move a pointer to the point of k and call it firstNode and then iterate over linked list again but this time second pointer secondNode will start from head and our first created pointer will start from its own place which we got from first iteration. and in this iteration we will move our firstNode till the last node of head. This is because when firstNode will hit the last  we will get the secondNode.


firstNode postion = k-1

secondNode position = count -k


Note: To keep the node position in check we will assign another pointer to firstNode and will be moving that in second iteration

Complexity

Space Complexity = O(1)
Time Complexity = O(N)

N is length of the linked list



Solution


class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if head is None:
return

firstNode = head

for i in range(1, k):
firstNode=firstNode.next

current = firstNode
secondNode = head

while current.next:
secondNode=secondNode.next
current = current.next

firstNode.val, secondNode.val = secondNode.val, firstNode.val

return head



Link to the qs in leetcode.

Comments

Popular posts from this blog

What is a Processor?

Smartphones have been the most important part of our lives. We have seen the evolution of our  handsets. First we saw landlines which were mess of tangled wires then we saw mobile phones which is successor of landlines. They were portable devices from which you can make calls then we witnessed emergence of Smartphones which were  considered as portable computers which also allows us to make calls. What is a Processor? Underneath that touchscreen display there is a full- fledged computer that commands your apps so that they function properly. A processor executes what you want your smartphone to do or in other word you can say processor is brain of computer. there is Exynos, Snapdragon, quad-core octa-core etc. What is a core? It is an element of surprises. They are present inside processor and are responsible for reading the command and executing them. First devices came with single core processor but later on scientists invented more advanced processors such as dual core , So...

Why 'C' is the default hard disk drive name

Computers have been really important part of our lives. Making our work easy and complete it in no time is the main advantage of computers. In the beginning computers were really expensive and were used by few people. Then with the increase and ease in technology computers became affordable and now-a-days everyone is using computers. Computers are proved as an evolution in our lives. Though you may be using computers but some of you may not be aware of some hidden facts. If you are using computers daily so here is one simple question for you. " Do you know why 'C' is the default hard dis drive and not 'A' or 'B'? Here is the answer : Hard disk drives became standard since 1980, Before Hard disk drives Floppy disk drivers were used as storage devices. Floppy Disk drives were initial storage devices. They came to existence in 1960's. They came in mainly 2 sizes, 5 1/4" and 3 1/2". These two floppy disk drives were labelled as Local Disk (A) and ...

Samsung launches CFG70 curved gaming monitors in India.

Samsung electronics launched its two gaming monitors in India on Thursday, LC24FG70 (24 inch) and LC27FG70 (27 inch)-priced at ₹ 35000 and ₹ 42000 respectively. The company claims that they are first curved gaming computer with a 1 millisecond moving picture response time (MPRT). These two monitors are part of CFG70 series of curved gaming computers which were launched in IFA 2016. Apart from ther fast response time with their VA panels, the both come with Quantum dot technologyand a 144 Hz refresh rate that is optimised for AMD's FreeSynch technology. Both the monitors support a full HD resolution, and company is touting a contrast ratio of 3000:1.Samsung is also boasting of a UX that's specially designed for gamers, with an "intuitive settings dashboard" as well as hotkeys on the front and back of the display to quickly adjust settings between presets. The company also says each monitor undergoes rigorous pre-shipment factory calibration for compatibility with vario...