Greatest Common Divisor of Strings - Leetcode 1071 - Python
Skills:
Python for Data80%
Key Takeaways
The video solves the Greatest Common Divisor of Strings Leetcode 1071 problem using a brute force approach and a greedy approach, implementing the solutions in Python.
Full Transcript
hey everyone welcome back and let's write some more neat code today so today let's solve the problem greatest common divisor of strings we're given two strings s and t and we say that t divides s if and only if one of the strings can be made up by adding the other string multiple times we could add it twice or three times or more times maybe even the two strings could be equal now given two strings our goal is to return the largest string X such that it divides both of these strings now that doesn't necessarily mean that string two will divide string one because as we can see from this second example we can't add this string twice to make this string but there exists a substring a b which can make this ring by adding it twice and can make this string by adding it three times and also don't let the problem trick you into assuming that string 1 is going to be longer than string two that's not necessarily going to be the case they just tell us we're given two arbitrary strings now there are many ways to solve this problem some can go really deep into the math but I'll keep it pretty intuitive you don't need super fancy math for my solution so how can we even Brute Force this problem well we can't just come up with our own random substring X let's try to take a substring from one of these two strings such as this one we can try a itself we can try this one it's length of one let's see if taking this and creating four copies of it because this string is length four we have to create four copies of this does that create this string well that would create a a a a a a that does not equal this string next we could try the first two characters which is of length two so how many times would we need to add it to make this string well we would need to add it twice because this is of length four so this is kind of where the math intuition comes in first of all we're trying substrings from this one why did I choose this one well because it's shorter than this one we know that if we get all the way up until here like this entire string and we tried every previous substring and none of those worked then creating a longer substring than this isn't going to work that type of X added together will never create this string because adding them together we have to create this string and we have to create this string so that's why we go with the smaller one though it doesn't make a huge difference I think but more importantly when we have a candidate X we take the length of this candidate X and we want to make sure that it is a factor of the length of this string because if it's not then it will be impossible to create this string such as for example if we had this string of length three adding this together will never create a string of length four we will though be be able to create a string of length 6 but that's not our goal here we need an X that can create both of these strings so another way to put it is when we have an X we take that length of it and we make sure that the length of this string which let's call L1 we can mod it by this length and when we mod it by this length there should not be a remainder so this should equal zero if it's not equal to zero we're not even going to try this candidate and we want to make sure the Sam is true for the other string too so we make sure to mod it by the length if it's not equal to zero then we don't do it but if it is equal to zero then we consider it and how exactly do we consider it well when we have a candidate like X how many times would we have to add X together to create a string of length four well we can get that by taking 4 and dividing it by the length of this candidate which is 2 that gives us two times two times x is going to create this string what about this guy well it has a length of six so we take six divided by two which we get the two from the length of X and then we get three so we need three copies of it to create this string and then all we do is check and then we just add it two times is it equal to this and add it three times is it equal to this guy if it is then we return the result one last thing we can do is that instead of going from smallest to largest we can be a bit greedy and try the longest possible one first because remember we're trying to find the largest X so let's start being greedy let's start with the four well four doesn't divide with six so we can't even try it then we try three well it doesn't divide with four then we try two yes it divides both of them and it does create both of them so that's what we would return immediately so to analyze the time complexity quickly since we're going to be iterating through the smaller string and checking in the worst case every sub substring of that that's going to be our X candidate we'll say that to do that we're going to need to iterate between the minimum of M and N where let's say m is the length of this guy and N is the length of this guy and then every time we do that in the worst case given a candidate X we're going to need to build this entire string which is of length n and we're going to need to build this entire string which is of length M and the time complexity to do that is going to be n plus M and we multiply these two together because this is what we're going to call inside of that Loop so this is the overall time complexity now let's code it up so we're going to start with the length of each substring and then we're going to iterate through where L this is an L maybe I should make a capital ball leave it lowercase for now L is in the range of the minimum of length 1 and length two and then we want to check if is divisor I'm going to create a helper function to do do this where the substring we can pick either one string one or string two because if it's a divisor of one it has to be a divisor of the other so we'll pick just arbitrarily starting with string one so a substring going from the beginning all the way to l oh and I forgot with our Loop we want to actually iterate not starting from zero but we want to start at the number itself and then iterate down going down negative one each time but this substring we picked it from string one we could have picked it from string two and the result would be the same because remember X whatever it is it has to go into both of the strings and that's what we're going to check in our is divisor function now if this were to return true that would mean we found our result because we're doing this in a greedy way so we would just return that string string one going from the beginning up until L and if we never find it out here then we can just return an empty string I think that's the default now to actually Define find our helper function let's call it is divisor it'll be given some length L first we want to check that L is a factor of the length of both strings the easy way to check that is length One modded by L so if this is non-zero or if this is non-zero then we know it's not a factor because it has to be zero so if it's not a factor of both of the strings then we just return immediately false we know it's not a divisor of both strings but if it is well at least the length of it is a divisor then we want to actually try to build the string but how do we build the string well I'm going to create a couple variables F1 and F2 these are going to be like the factors I guess I should write out the entire variable but I really hate writing out variables in leak code so to get F1 we're just going to take the length of string one and divide It by L we're doing integer division in Python because we need to round down while this would never be a decimal anyway because we made sure that it is a factor so I guess you don't really need that but I'll leave it anyway L2 divided by L so these are going to be the factors this is going to tell us how many times we have to multiply so when we take string that substring we were talking about our candidate L this is it we're going to multiply that by f 1 and we want to make sure that this is equal to string one and we also want to make sure that this is true for string two so here we just change this to F2 and we change this to string two you could say we need to change this to string two you could it would work but it'll work in both cases because remember our candidate is going to be the same for both strings anyway and if both of these are true we return true if they're not we return false so we can literally just return this entire value oh and I quickly I just noticed that here we're passing in the string we don't want to do that we want to pass an L itself so this is is the entire code 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
Solving Greatest Common Divisor of Strings Leetcode 1071, today's daily leetcode problem on January 31st.
🥷 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://neetcode.io/problems/greatest-common-divisor-of-strings
0:00 - Read the problem
1:10 - Drawing Explanation
5:32 - Coding Explanation
leetcode 1071
#neetcode #leetcode #python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeetCodeIO · NeetCodeIO · 14 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
▶
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: Python for Data
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
1:10
Drawing Explanation
5:32
Coding Explanation
🎓
Tutor Explanation
DeepCamp AI