Largest Substring Between Two Equal Characters - Leetcode 1624 - Python
Key Takeaways
The video demonstrates a solution to the Leetcode 1624 problem, 'Largest Substring Between Two Equal Characters', using a hash map to track the first occurrence of each character in the string and calculate the maximum length of the substring between two equal characters. The solution is implemented in Python and has a time complexity of O(n) and a memory complexity of O(1).
Full Transcript
hey everyone welcome back and let's write some more neat code today so today let's solve the problem largest substring between two equal characters we're given a string s which consists of only lowercase characters A through Z and we want to find the length of the substring between two characters that are equal so the longest substring that we can find like that so imagine we have a string like a b c d e a b c and then B to find a substring first we have to find two copies of the same character suppose these two they're both a what's the length of this substring and when they say length of substring they actually mean only the characters in between them so how many characters are between them well in this case there are four so is this the longest such substring because all we have to do is return the length of the longest substring there are two B's as well so we have a b here and a b here the number of characters between them is five and I think we also have two C's but the number of characters between them is three so obviously the longest is five that's what we would return now the question is how can we find the solution to this problem like how do we find that longest substring the first way that you might try is like a Brute Force approach for example starting at this a keep basically two pointers keep one pointer here and then this pointer will keep shifting through the string until it lands at another a and then we'll take the length between these two but one thing I think this problem actually doesn't clarify or at least doesn't make clear is what if we actually had another a over here does it allow us to consider this but also to consider this even though there's an a between them like does the characters in between have to be nonas in this problem actually this is perfectly valid it doesn't matter if there's an A in between these two there doesn't need to be other characters only it's a little open open ended but I think this sentence does uh support that knowing that the approach that I was kind of talking about right now is a Brute Force approach where we'd consider this character and then we'd consider this next character and then we'd consider the next character and keep going that would be an O of N squared approach but is it possible for us to do better is it possible for us to do this problem in a single pass well it would be hard with two pointers wouldn't it if we had one pointer here and we're iterating over these yes we know we've seen a b we know we've seen a d a c but by the time we get to this C for example how do we know that we have already seen a c before we'd have to probably put these characters somewhere in memory but not only that we'd have to also remember at what index did we see the C and it would be at index 0 1 two and of course we would probably know which index we're currently at we can do that with a single index or pointer I so if we can find a way to keep track of all the characters that we've seen before and map them to the index that we've seen we can solve this problem there's one last Edge case though and that is let's say the third occurrence of an a character over here we have actually seen two A's before so when we're here how do we want to calculate the window do we want to calculate it with the last a that we've seen or do we want to calculate it with the first a that we've seen probably the first a so when we take these guys and throw them into the data structure that we're going to use which in my case I'm going to use a hash map because like I said we want to map every character to the index so a would be mapped to zero B would be mapped to one etc etc when we get to the second occurrence of the a yes we're going to calculate the length of the substring we're going to see okay there's four characters in between them and by the way we would do that with 0 over here I think this is going to be a five we'd say 5 - 0 and then minus another one because we're only counting the characters in between them so that's going to be the formula by this point though when we get to the second a we calculate the length of the substring but we don't take this a and throw it in the hash Mount because there's already an a there we only want to keep track of the first occurrence of each character that will allow us to solve this problem optimally and we will do it in bigo of n time in terms of memory complexity you might think it's Big O of n but recall that the input string will only contain lowercase A through Z so that's technically 26 so this is actually constant memory now let's code this up so the first thing I'm going to do is create that hashmap where we are mapping every character to the first index that it occurs at so I'm going to call this map character index it's going to be just an empty hash map initially we also know that we're trying to calculate the max length between characters equal characters so that is going to be our result I'm not going to initialize it to zero because actually they tell us in the problem description that we should return netive -1 if a valid result does not exist so that is what I'm going to initialize it to I'm going to return it here and now the only thing left for us to do is actually calculate it I'm going to do a little shortcut in Python I see in enumerate this string if we were to iterate over this string we could iterate over just the character or we could just get the index by doing a range function and taking the length of this string but we can get both of those in one line if we use enumerate I'm going to do that and now we know that there's a couple cases have we seen this character before is this character in the character index map or is it not in the character index map we know the else case is pretty easy because if it's not the only thing for us to do is just throw it in there put this character and say that this is the first index that it occurs at we can't calculate the length of a substring because we've only seen this character once so far but this case is a bit more interesting if the character already exists here and now we have seen it again that means we can calculate the length between these two characters how do we do it well we take the index of the current character I subtracted by the index of the first time that we saw this character and also subtract one from it to get the number of characters in between them and this is the length between them now we want to maximize our result so we set result equal to the max of itself and what the current length between the characters happens to be this is the entire code let's run it to make sure that it works as you can see on the left yes it does run time doesn't look good but that's pretty random on leak code so I'm not going to pay attention to it if you found this helpful please like And subscribe if you're preparing for coding interviews check out ncode doio 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/
🥷 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/largest-substring-between-two-equal-characters/
0:00 - Read the problem
0:12 - Drawing Explanation
4:43 - Coding Explanation
leetcode 1624
#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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
Design Linked List - Leetcode 707 - Python
NeetCodeIO
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
LFU Cache - Leetcode 460 - Python
NeetCodeIO
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
IPO - Leetcode 502 - Python
NeetCodeIO
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
Sort an Array - Leetcode 912 - Python
NeetCodeIO
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO
More on: Algorithm Basics
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Bloom Filters, Explained Properly
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Medium · Python
Chapters (3)
Read the problem
0:12
Drawing Explanation
4:43
Coding Explanation
🎓
Tutor Explanation
DeepCamp AI