Maximum Twin Sum of a Linked List - Leetcode 2130 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

The video solves the Maximum Twin Sum of a Linked List problem on LeetCode 2130 using the two-pointer technique and linked list modification, implementing a solution in Python.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum twin sum of a linked list we're given a linked list of even length that's going to be really important here and that's because every single node in our linked list is going to have a corresponding node on the other side of the linked list so the first node is going to be paired with the last node the second node is going to be paired with the second to last node and if we had additional nodes like in the middle they would be paired together with this same pattern now among all of these pairs we want to determine the one that has the maximum sum so not super crazy one possibility would be this pair add those values together we get five plus one that's equal to six that's our maximum so far but let's try every other pair in this case so we only have one other pair four plus two add those together we get six once again so in both cases six is the maximum and that's what we're gonna return but maybe in between we actually have another pair of nodes and those values are like five and seven or something like that then we would take that pair of values see what the sum is it's five plus seven which is twelve that's the new maximum and that's what we would return so among all these pairs we just want to return what the maximum sum is and then return it now what's going to make this challenging is that we have to pair the first value with the last value and then we're basically doing a two pointer technique where we're taking these pointers and then shifting them inwards and the only reason this is challenging is because we have a linked list it's hard to travel in reverse on a linked list if it's not doubly linked one in a way to get around this would be to just dump all of these values into an array then we can use the two pointer technique pretty easily the downside is that we would need another data structure so we would need o of n memory now is it possible to do this without doing that well it's gonna be pretty much impossible to Traverse this in reverse order if the pointers are like this so if we are allowed to modify the linked list then we actually can solve this without additional memory we can do it with constant memory let me show you how we can do that as you might guess basically if we need to reiterate through this from left to right we can do so we can follow these pointers but if we need to iterate through this in reverse order we have to take every pointer and reverse it so we have to do this before we can do our two pointer technique but this isn't going to be super hard we would just keep going going until we got to the middle of the linked list or the second half of the linked list and then Traverse through it and reversing every link and then by the time we got to the end we'd have a reference to this node anyway so then we'd just be able to reiterate through this and iterate through this at the same time now I'm going to actually do a slightly different approach because it's a little bit easier to code up in my opinion and that is I'm going to take the first half of the array and reverse it so what I'm actually going to get is something like this where we take this pointer and point it backwards which in this case is going to point at null and take this pointer and make it point back at the previous node so this is a bit cleaner diagram but now by the time we do this we will we'll do this as we iterate through the linked list so we'll stop once we get to the Midway point and then we'll have a reference to this node and we'll have a reference to this note if we stop at the Midway point and then we'll iterate through these guys in order and we'll go outwards so this will accomplish the same thing it's just that instead of going from out to in we're going from in to out and then we'll be able to get the sum of every single pair and figure out which one is the maximum now the only thing is how do we actually get to the middle of the linked list because we don't have the length of it initially we could compute the length and then find the middle but there's actually a faster or rather a simpler way to do it which is called the two pointer technique which is slow and fast pointer the idea is that if we have two pointers slow and fast if we initialize them to the beginning of the linked list and we increment the slow pointer by one every single time and we increment the fast pointer by two every single time by the time the fast pointer reaches the end of the linked list or it reaches out of bounds of the linked list which would happen in this case so one more iteration we'd move the slope pointer here we'd move the fast pointer twice so move it out here so slow pointer would stop here our fast pointer is out of bounds every time this is going to happen the slow pointer is going to end at the beginning of the second half of the linked list so we can use this to our advantage because that's exactly where we would want to stop anyway and we're also told that the linked list is always going to be of even length so we don't really have to worry about the case where the linked list is of odd length now let's code this up time complexity is Big O of n because yeah we kind of have to iterate through the linked list twice but that's still linear time and we don't need any extra memory so it's constant memory so just as I said we're going to first initialize a couple pointers slow and fast they're both initially going to be at the beginning of the linked list and all we're trying to do so far is just get to the middle of the linked list and reverse the first half of it I'm also going to keep track of a previous pointer that's going to help us actually reverse the nodes so while our fast pointer is non-null and fast dot next is non-null then we want to continue for the fast pointer it's pretty simple we just want to shift it to the right twice we can do that by setting it to fast.next dot next because we guaranteed that the next pointer is going to be no no we don't know about this this might be null then we also want to set the slow pointer equal to slow dot next but we can't quite do this because we'll still need a reference to the slow pointer before we even do this we want the previous to be set to the slow pointer and actually for this node slow we actually want to set slow dot next equal to the previous node so if we do that we'll have overwritten in the values so we actually have to store this in a temporary variable so slow dot next will be stored in temp but after we reverse it we'll set its next pointer to the previous node then update the previous node then we want to set slow to slow.next but not the overwritten value we don't want to set it to previous we want to set it to the actual next node which we saved in temp so I'm going to do just like that then we're going to actually get our results so we'll set it to zero initially but notice how by the time this is completed the fast pointer will either be at the last note or out of bounds since the list is always of even length our fast pointer is always going to be out of bounds but the slow pointer as I showed in the diagram is going to be at the beginning of the right half of the linked list and the previous pointer is just going to be one behind that which in our case is going to be the beginning of the left half of the linked list using that and using the fact that both of of them are of even length we'll just pick the slow Pointer while it's non-null we could have picked the previous one it doesn't really matter both of the linked lists are of even length then we're going to set the result equal to the max of either itself or the current sum which we can get by taking the previous Value Plus the slow value and adding them together this is the left linked list this is the right linked list we're trying to figure out what the max is and we're also going to have to update the pointers accordingly at this point you don't even need to know which one is the left half and which one is the right half because we're just going to shift the pointers the same regardless slow slow dot next and then we will have our maximum and we can go ahead and return it so that's the entire code now let's run it to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🥷 Discord: https://discord.gg/ddjKRXPqtk 🐦 Twitter: https://twitter.com/neetcode1 🐮 Support the channel: https://www.patreon.com/NEETcode ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf 💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1 Problem Link: https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ 0:00 - Read the problem 0:30 - Drawing Explanation 5:45 - Coding Explanation leetcode 2130 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 47 of 60

1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to solve the Maximum Twin Sum of a Linked List problem on LeetCode 2130 using the two-pointer technique and linked list modification, with a Python implementation. The problem requires finding the pair with the maximum sum in a linked list of even length. The solution uses two pointers to traverse the linked list and find the maximum sum.

Key Takeaways
  1. Iterate through the linked list from left to right
  2. Reverse the first half of the linked list to allow traversal in reverse order
  3. Use two pointers to find the pair with the maximum sum
  4. Initialize slow and fast pointers to the beginning of the linked list
  5. Increment slow pointer by one and fast pointer by two to find the middle
  6. Reverse the first half of the linked list using a previous pointer
💡 The two-pointer technique can be used to traverse a linked list in reverse order by reversing the first half of the linked list.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (3)

Read the problem
0:30 Drawing Explanation
5:45 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →