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

How to bypass Android pattern lock using CMD.

Many of you have encountered the situation where you forget your phone's pattern lock. This is totally common and we can't deny this. Then after trying all the combinations in mind and losing hope we just choose to reset our phone. But here I am providing you with the solution to this problem. You can just open up your phone following these few steps and without undergoing any trouble of losing your data and wasting your time.  Yes, I am talking about bypassing the pattern lock you used to unlock your phone. This procedure will be done using CMD. CMD, also known as command prompt is an amazing tool provided in Windows OP. You can control your entire computer using CMD which includes copying files from one folder to another, hiding your files, checking details of connected wireless devices and even shutting down your PC. You just need to learn some easy commands. How to bypass Pattern lock on your Android Phone? Before trying to Bypass the pattern lock...

1235. Maximum Profit in Job Scheduling

Hi everyone, Today's post is little bit intriguing to me as it took me some time to get t the solution. I have been out of practice for a bit so I was not able to do it in the DP. I didn't want to copy the code. Though i understood the code after i checked its solution in the discussions. Anyways, i tried to do it with heap and with some thinking I was able to do it and with my surprise It performed real well. I would like to jump to the solution but first I would like to explain a little bit about heaps so you can get better understanding of the code. A heap is like a special type of list where the smallest (or largest) item is always at the front. Think of it like a priority line at a theme park, where the person with the highest priority goes to the front. There are two types of heaps: Min Heap: The smallest item is at the front. It's like standing in a line where the shortest person is always at the front. Max Heap: The largest item is at the front. It's like stand...