Get Equal Substrings Within Budget - Leetcode 1208 - Python

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

Key Takeaways

The video solves the Leetcode 1208 problem, 'Get Equal Substrings Within Budget', using a sliding window approach and optimizing the solution by shifting the starting point of the substring to the right. The problem is to find the largest substring that can be transformed from s to t within a given budget, where the cost of transforming each character is the absolute difference between their ASCII values.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem get equal substrings within budget we're given two strings of the same length and an integer Max cost consider this example where the Max cost given to us is equal to three so the question we want to know is how large of a substring can we take from s and transform it into the same corresponding substring in a t so for example this substring corresponds to here and if we want to change this one to this one we have to change this a to a b and this B to a c and this C to a d The Catch here though is it's going to take us some cost to change each character and in this problem we're taking the asy value of lowercase a and the aski value of lowercase b taking the difference between them and then getting the absolute value because we don't want to deal with negative integers so in this case it's going to be one this one is going to contribute to our total cost so initially our cost was zero and now our total cost changing it to a b is going to be total cost of one so we just want to stay within this budget and we want to try to create the largest substring that matches in both strings let's try to think about the brute force and then see if we can optimize it at all first of all just to simplify this problem let's do a little bit of precomputation I'm going to take both strings and I'm just going to take the difference between each corresponding pair of values so the difference between a and b is going to be one B and C is going to be one C and D is also going to be 1 D and F is going to be two now just in case you're wondering how am I calculating those differences well just think of it as this a b c uh d e f i don't want to talk too much about like what aski values are so I'm just going to kind of give you the very simple explanation the difference between two characters is pretty much just like the distance between them in this string so A and B the distance is one obviously what's the difference between D and F Well the distance between those two is going to be two now that we have this we kind of don't even have to think about like the original string so just this is kind of the more simple way to think about it at least for now so now consider this let's just go through every single substring so this sub string has a cost of one so of course we can stay within our budget this substring has a cost of two we can stay within our budget this substring has a cost of three we can again stay within our budget this is the longest string so far by the way right like the length of it is what determines the result that we want to return we're not returning the cost we're returning the length of that string in this example it just happens to be the same then we try the next one this one of length four but the total cost of that is five right we're getting the cost by taking the summation of these values so this one doesn't work and pretty much like even if there were additional values here 1 2 3 whatever we're not going to find any substring starting from here that is now going to be valid because all these values are going to be positive or maybe they're going to be zero but basically if this one is not valid nothing bigger than that is going to be valid then we would continue our Brute Force now let's get all substrings starting from here so this one this one this one and we'd keep doing that you might kind of notice that there is a bit of repeated work here while the solution this Brute Force solution does work it's going to be o of n^2 cuz that's roughly how many substrings there are going to be here but like I said by the time we got here we know this is invalid right so why do we decide to start back here from the beginning and then try to build longer substrings when we don't need to we already found one of size three we tried one of size four it didn't work out for us how about we just shift from the left how about we take that shortcut and now consider this substring the reason we skipped this one and this one is because even if those two were valid they would never be the result we already found one of size three now we're trying to find another one and we're trying to shift from the left as little as we can to make our window valid so at this point if you're familiar with what a sliding window is you probably are convinced that that is the solution to this problem which it is so that's how we're going to solve this problem from here what we would do is shift left here so now we're going to be here this is still invalid though we're going to keep track of what the total cost is right now it's four again we're going to shift left and we're going to decrement whatever value we removed from the current window so now our cost is three this window is valid but it's smaller than the pre window that we were looking at of size three and at this point we're going to try to increase our window now cuz we are within the budget it could be possible there are some zeros over here but there's not so we pretty much have exhausted every possibility so this is the linear time approach now if we create an array like this and we just ignore the two input arrays it works but it's extra space it's linear space so we actually don't need to do this I just showed it this way because that's kind of a simpler way to visualize it we will actually be computing these values on the Fly which is really easy to do just by taking the asy values of these and just taking the difference between them and then getting the absolute value between the difference I think that will make more sense in the code and that will make this a constant space solution let's code it up the main thing here is first of all keeping track of like the current total cost I'm going to have a variable for that I want to make it like this I want to spell it like snake case but that's going to be inconsistent with what the parameter is so I'm just going to do it this way and I'm going to declare our left pointer so this is going to be kind of like the window I was showing you earlier I know I'm not like entirely introducing to what the sliding window is I have plenty of videos on that though and I have like a course that goes pretty in depth on that as well lastly we know that the result we're trying to return is what the largest window actually is the largest substring that we can replace so that is what we're going to try to maximize that's what we're going to end up returning so now let's say for our right pointer in in the range of every position in the input string both of them are the same length so we can do either one here and what we want to do like I said is compute the cost on the Fly what is the cost of this current position that we're adding to our window well let's get the asky value of one of the characters from one string s at index R and let's get the asky value from the other string T at index R same position in both strings though and or it is just how you get the asky value we don't know if this is positive or negative so let's just get the absolute value let's call this the cost and this is what we're going to end up adding to the current cost I guess we actually don't need a different variable so let's just take this and add it to the current cost okay now it could be possible well what we want to do we want to maximize the result right let's assume our window is valid this is what we would do we would set result equal to the max of itself or the current window size size we can compute that by taking the right pointer minus the left pointer plus 1 this is how you compute the size of a substring with the two end points so this is what we would do if our window is valid but it's possible our window could be invalid by adding this new character how do we make it valid again well first of all how do we know if it's invalid it would only be invalid if the current cost is greater than the Max cost if they're equal that's actually perfectly fine but if the current cost is greater that's a problem while this is the case because it might take us multiple characters to remove to make the cost valid so while this is the case we are going to shift the left pointer we're going to increment the left pointer by one but we don't want this Loop to run infinitely so before we actually increment the left pointer let's subtract from the current cost the cost of that character which again we can just compute on the Fly I'm going to copy and paste this part over here but remember we're not removing the right character we're removing the left character so let's change these pointers to left here and left there so believe it or not this is the entire code I'll run it to show you that it works and you can see it works it's pretty efficient in case you're not convinced that this is linear time some people say well you have nested Loops that must mean it's n s no because our right pointer is going to iterate over the entire size of the input our left pointer is also going to iterate in the worst case through the entire string it's not like we're resetting the left pointer back to zero every single time down here if I put left is equal to zero every single time then maybe it would be n s but we're not resetting it so this is not N squared if you found this helpful check out N.O thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/get-equal-substrings-within-budget/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 5:45 - Coding Explanation leetcode 1208 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
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
47 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

The video teaches how to solve the Leetcode 1208 problem using a sliding window approach and substring optimization techniques. It provides a step-by-step guide on how to implement the solution in Python and explains the key concepts and ideas behind the algorithm.

Key Takeaways
  1. Calculate the difference between each corresponding pair of values in the strings
  2. Go through every single substring and calculate its cost
  3. Shift the starting point of the substring to the right
  4. Use a sliding window approach to find the largest substring within a budget
  5. Compute the cost of the current position on the fly
  6. Maximize the result by returning the largest window size that is valid within the budget
💡 The sliding window approach can be used to optimize the solution by reducing the number of substrings to be considered and minimizing the time complexity.

Related Reads

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 →