Shortest Way to Form String

  Рет қаралды 28,635

Kevin Naughton Jr.

Kevin Naughton Jr.

Күн бұрын

For business inquiries email partnerships@k2.codes SOCIAL
----------------------------------------------------------------------------------------------------------------
Instagram: / kevinnaughtonjr
Twitter: / kevinnaughtonjr
Patreon: / kevinnaughtonjr
Merch: teespring.com/stores/kevin-na...
GitHub: github.com/kdn251
MUSIC
----------------------------------------------------------------------------------------------------------------
xo bored llif3 by young frontwood
/ xo-bored-lif3

Пікірлер: 83
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
IS IT JUST ME OR DO I LITERALLY LOOK LIKE A GIANT SITTING AT THIS DESK??? instagram: instagram.com/kevinnaughtonjr/ twitter: twitter.com/kevinnaughtonjr merch: teespring.com/stores/kevin-naughton-jrs-store patreon: www.patreon.com/KevinNaughtonJr
@Archcorsair
@Archcorsair 4 жыл бұрын
Yes.
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
Daniel S ok so it’s not just me
@surendra9935
@surendra9935 4 жыл бұрын
We are with you too dude
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
Surendra hahaha
@saumya1singh
@saumya1singh 3 жыл бұрын
@@KevinNaughtonJr KZbin showing "You can not donate in this country or region?" 🤔
@anandprakash4995
@anandprakash4995 4 жыл бұрын
You are Awesome ! Crystal clear explanation !! learnt a lot !!
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
Anytime and happy to hear that thanks :)
@Mai_Bharatwaasi
@Mai_Bharatwaasi 3 жыл бұрын
Thanks a lot Kevin!! you are doing great :)
@idemchenko-js
@idemchenko-js 4 жыл бұрын
Hey Kevin, you've listened to your audience, no candles this time :) people were getting nervous :) Thanks for your videos, you're doing a great good!
@rmadhavmca1
@rmadhavmca1 4 жыл бұрын
thanks for adding videos frequently. I really appreciate it.
@RafaelBritodeOliveira
@RafaelBritodeOliveira 4 жыл бұрын
me too
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
you got it
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
@@RafaelBritodeOliveira anytime!
@bdc225
@bdc225 4 жыл бұрын
Good stuff again man 🤝
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
thanks
@casual_chess
@casual_chess 4 жыл бұрын
Thank you for these videos sir❤
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
Anytime thanks for the support
@prakad97
@prakad97 4 жыл бұрын
Nice.. appreciate the regular uploads man..!!
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
you got it!
@faraz7409
@faraz7409 4 жыл бұрын
my man! thanks for the vid very helpful!
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
anytime Faraz thanks for the support!
@somasishsahoo
@somasishsahoo 4 жыл бұрын
Hi Kevin, Appreciate all your efforts in making these videos. Have cleared a lot of my doubts. Regarding this algo. I can say that one of the case is missing. Inner while loop has to be broken if char are mismatch. Example - Source - "pabc" , Target - "abcpbc" - O/P - 3 but above program o/p is 2 a break statement will resolve this. Thanks Som
@ShaliniNegi24
@ShaliniNegi24 3 жыл бұрын
Such an elegant solution it is! Thanks for the videos
@KevinNaughtonJr
@KevinNaughtonJr 3 жыл бұрын
Shalini Negi anytime! If you like my explanations be sure to sign up for the interviewing service I created thedailybyte.dev/?ref=kevin I recommend joining a premium tier if you can!
@ShaliniNegi24
@ShaliniNegi24 3 жыл бұрын
@@KevinNaughtonJr sir, Surely I will try.
@KevinNaughtonJr
@KevinNaughtonJr 3 жыл бұрын
Shalini Negi amazing can’t wait to see you join :)
@VilliSopuli
@VilliSopuli 3 жыл бұрын
Do you think it would work / be any faster to have a Hashmap mapping all the characters in the source mapping to a list of integers (indices they appear at)? So they idea would be that instead of always looping thru the whole source string char by char, just looping through the occurrences of the chars and forming the subsequence starting from those indices and calculating their length and then comparing and using the longest subsequence and then moving on to the next remaining. I wasn't able to see this problem since I'm not a premium anymore.
@jaatharsh
@jaatharsh 7 ай бұрын
awesome well explained, thanks buddy
@ChocolateMilkCultLeader
@ChocolateMilkCultLeader 4 жыл бұрын
so when you do charAt(i++) it first evals charAt(i) and then increments i?
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
devansh yep!
@TheRaviraaja
@TheRaviraaja 3 жыл бұрын
will binary search on target string will help in reducing time complexity. O(nm) is very high
@raviashwin1157
@raviashwin1157 4 жыл бұрын
what was that song played at the beginning of the video?
@renetchi
@renetchi 3 жыл бұрын
How about storing the source as hashmap and then looping all target, if current target is in source hashmap then continue to next target. If current target location in source is smaller than prev one then add the total count
@divyanshukr
@divyanshukr 4 жыл бұрын
Hey Kevin, can we also do this in O(m log n) time? I am thinking we can keep a sorted list of positions of each char in source( O(n) time and O(n) space, preprocessing). Then for each char in target, we just have to find the same char's next greater position in source (greater than the index we found in source for the previous char of target). Since each char's index list is sorted, this can be done in log n time. Therefore, m chars in target and for each char log n search time = O (m log n).
@vaibs1001
@vaibs1001 4 жыл бұрын
Thought of the same, here is the code for it : int shortestWay(string source, string target) { int sourceLen = source.length(); int targetLen = target.length(); vector srcCharPos(26, vector()); int minSub = 1; for (int i = 0; i < sourceLen; ++i) { srcCharPos[source[i] - 'a'].push_back(i); } int prevCharIndex = -1, j = 0; while (j < targetLen) { int charIndex = target[j] - 'a'; auto it = std::upper_bound(srcCharPos[charIndex].begin(), srcCharPos[charIndex].end(), prevCharIndex); int index = it - srcCharPos[charIndex].begin(); if (index >= srcCharPos[charIndex].size()) { if (prevCharIndex == -1) return -1; minSub++; prevCharIndex = -1; } else { prevCharIndex = srcCharPos[charIndex][index]; ++j; } } return minSub; }
@tusharmarda295
@tusharmarda295 4 жыл бұрын
Worst case time complexity can be improved to O(sourcelength + targetlength * log(sourcelength)), though not required for such small input sizes. First you create a map from char in source to a sorted array of indices in source where that char occurs. This will take one scan of source. Then, while forming substrings, you can directly use binary search on the array of the character you are trying to insert into the substring.
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
Nice!
@jkrw3540
@jkrw3540 4 жыл бұрын
good, I had the same solution in my mind, BTW, how to do that if this time we can concatenate substrings and not subsequences?
@sabisyed
@sabisyed 3 жыл бұрын
can be done in linear time. Create a map of char to integer of source. Then check target's character appear in map and do not update your counter as long as character of target string is always appearing at > prevIndex +1 . private int formString(String source, String target) { if(source.isEmpty()) { return -1; } Map charMap = new HashMap(); for(int i = 0; i < source.length(); i++) { charMap.put(source.charAt(i), i); } int count = 0; int countSubString = 0; int index = -1; boolean MultiCharacterSubsequenceBeingBuilt = false; int lengthOfSubSequence = 1; for(int i = 0; i < target.length(); i++) { if(charMap.get(target.charAt(i)) == null) { return -1; } int mapIndex = charMap.get(target.charAt(i)); count++; if(index == -1) { index = mapIndex; } else if(index > mapIndex -1) { index = mapIndex; MultiCharacterSubsequenceBeingBuilt = false; count = count - (lengthOfSubSequence - 1); lengthOfSubSequence = 1; } else if(index 1) { count = count - (lengthOfSubSequence - 1); } return count; }
@raviapiit
@raviapiit 4 жыл бұрын
I think, we don't need StringBuilder, because that was just being used for retrieving subsequence length. This will improve overall performance IMHO. Btw, great work. :)
@dipteshsil9299
@dipteshsil9299 4 жыл бұрын
Was wondering if we need the subsequence string. We can avoid that. That way we will be able to improve efficiency.
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
I think we need it cuz otherwise how do we remember what character we're gonna take on each iteration?
@dipteshsil9299
@dipteshsil9299 4 жыл бұрын
@@KevinNaughtonJr we can simply use the j variable. not reset to 0. line 5 reset to while( j < target.length() )
@jasminegeorge1149
@jasminegeorge1149 4 жыл бұрын
@@KevinNaughtonJr Here is the code without using subsequence, we can keep track using only j while(j
@ozgurgonen9061
@ozgurgonen9061 3 жыл бұрын
yup, just uses the length() method, so an int "len" would be enough
@kumarc4853
@kumarc4853 3 жыл бұрын
looks like this can have constant space by using a counter rather than a builder. TThank you for the video.
@AshokBathini
@AshokBathini 4 жыл бұрын
@All- How about this? I felt this is easier to understand. Do u see any bugs in this code? T: O(target.length + source.length) S: O(1) = space for 26 ints to store indexes of all characters. Note: assumes no duplicates in source string. public static int countSubsequences(String s, String t) { if (s == null || t == null || s.length() == 0 || t.length() == 0) return 0; //maintain indexes of all characters of source int[] spos = new int[26]; for (int i = 0; i < s.length(); i++) { spos[s.charAt(i) - 'a'] = i; } int prevPos = -1; int count = 0; for (int i = 0; i < t.length(); i++) { int pos = spos[t.charAt(i) - 'a']; //if the current character in target is out of sequence, then it's a fresh beginning of another sequence. if(pos
@renetchi
@renetchi 3 жыл бұрын
Maybe need to store array of array for spos since the source length can be 0-1000
@lazzuuu21
@lazzuuu21 Жыл бұрын
What if the source contains a same character? like "aab" and the target is "aaa"? the answer would be 2, but your answer will return 3(?)
@JSDev776
@JSDev776 3 жыл бұрын
so this is basically the greedy approach, match the longest sequence possible and repeat, but can there be a situation where you need to stop before matching further down and match from start again?
@surendra9935
@surendra9935 4 жыл бұрын
Thank you Kevin. I pinged you in instagram to make a motivational video. love 💙 you and your videos. Take Care 😃
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
thanks for reaching out!
@aliara1568
@aliara1568 4 жыл бұрын
def shortestWay(source: str, target: str) -> int: res = 0 i = 0 while i < len(target): exists = False for j in range(len(source)): if i < len(target) and source[j] == target[i]: exists = True i +=1 if not exists: return -1 res +=1 return res source = "xyz" target = "xzyxz" shortestWay(source, target)
@charan775
@charan775 4 жыл бұрын
wow thanks for the video. but these are premium questions right? you uploading them isn't a problem?
@godismygeneral
@godismygeneral 4 жыл бұрын
Hey Kevin what is the runtime of this algo?
@utalmighty
@utalmighty 3 жыл бұрын
Probably O(nm) n length of source m length of target
@vaishali874
@vaishali874 4 жыл бұрын
can we use a subsequence more than once?
@kumarc4853
@kumarc4853 3 жыл бұрын
yes
@surepasu
@surepasu 3 жыл бұрын
I think the solution not working for below test cases..please correct me if I am wrong For this scenario it should return -1 , but returning 2 # sourcestr = 'abc' # targetstr = 'abcbc1' For this scenario it should return 3 , but returning 2... sourcestr = 'adbcklm' targetstr = 'aklmbc'
@Brodskyb523
@Brodskyb523 3 жыл бұрын
For your first test case, the problem states that "Both the source and target strings consist of only lowercase English letters from 'a'-'z'." So, your input should not contain the number "1". For your second test case, it should in fact return 2, not 3. This is because of the following: "aklm" + "bc". On the first pass, you can take "aklm" because they are in that order in the source, and then when you have to check the source a second time, you get the "bc".
@zn4798
@zn4798 3 жыл бұрын
Brute force TLE!
@shriharikulkarni3986
@shriharikulkarni3986 2 жыл бұрын
TC is O(mn), not accepted in interview.. Can you please post O( n log m ) explanation
@abhinavgupta750
@abhinavgupta750 3 жыл бұрын
Can source have character duplication?
@chrisy.703
@chrisy.703 2 жыл бұрын
excellent greedy method
@ShivamGupta-dm7kf
@ShivamGupta-dm7kf 19 күн бұрын
I want your song playlist pls
@sharkk2979
@sharkk2979 3 жыл бұрын
How u come up with a solution? I am binge watching ur videos.
@sureshchaudhari4465
@sureshchaudhari4465 2 жыл бұрын
with due respects sir why i am stuck while forming logics for such questions kindly help
@zhakaske5671
@zhakaske5671 4 жыл бұрын
It doesn't work for s="abcd" and t="adcb", answer must be 4, and not 3, you need to adjust the inner loop to break when there is mimatch.
@Brodskyb523
@Brodskyb523 3 жыл бұрын
That's wrong. It should be 3: "ad" + "c" + "b"
@scnullois
@scnullois 4 жыл бұрын
This is decent approach but you can probably do better by factoring out the section that finds the largest subseq into a dynamic programming problem which memoizes the sub-problems.
@vk1618
@vk1618 4 жыл бұрын
Check alternate soln
@rahulshrivastava3040
@rahulshrivastava3040 4 жыл бұрын
Kevin, Is there a lot of value in going through your videos or any tech interview videos, knowing that current situation will halt all hiring. Do not get me wrong, your videos are fantastic.
@gnanyreddy3030
@gnanyreddy3030 2 жыл бұрын
same idea efficient implementation int shortestWay(string source, string target) { int m = source.size(); int n = target.size(); int i=0, j=0; bool found = false; int res = 0; while (j
@harsha2s2udupa
@harsha2s2udupa 4 жыл бұрын
I think this would fail if the source string is "abcabcd" and target is "abcd" .
@ShaliniNegi24
@ShaliniNegi24 3 жыл бұрын
I was also thinking of this test case :/
@ShaliniNegi24
@ShaliniNegi24 3 жыл бұрын
For even this case also source: "dfed" target: "fed"
@-harshayadav
@-harshayadav 3 жыл бұрын
@@ShaliniNegi24 why will it fail? i guess it works perfeclty fine
@krishnamohansharma8859
@krishnamohansharma8859 4 жыл бұрын
Put the code on your github. It's nowhere to be found
@pratikchowdhury9210
@pratikchowdhury9210 4 жыл бұрын
Lol that 1 dislike wonder why
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
it was me
@wian7284
@wian7284 4 жыл бұрын
@@KevinNaughtonJr 😂😂😂 You dint seriously say that! GENIUS!!
@KevinNaughtonJr
@KevinNaughtonJr 4 жыл бұрын
wian haha I’m jk
Astroid Collision
13:42
Kevin Naughton Jr.
Рет қаралды 32 М.
Reorganize String
12:44
Kevin Naughton Jr.
Рет қаралды 77 М.
Fast and Furious: New Zealand 🚗
00:29
How Ridiculous
Рет қаралды 45 МЛН
What it feels like cleaning up after a toddler.
00:40
Daniel LaBelle
Рет қаралды 92 МЛН
Mom's Unique Approach to Teaching Kids Hygiene #shorts
00:16
Fabiosa Stories
Рет қаралды 39 МЛН
Longest String Chain - Leetcode 1048 - Python
15:34
NeetCodeIO
Рет қаралды 8 М.
Easy Google Coding Interview With Ben Awad
28:00
Clément Mihailescu
Рет қаралды 1 МЛН
Maximum Length of a Concatenated String with Unique Characters
11:59
Kevin Naughton Jr.
Рет қаралды 75 М.
Spiral Matrix
10:16
Kevin Naughton Jr.
Рет қаралды 45 М.
How I Failed the Google Coding Interview (and lessons I learned)
14:24
SHORTEST WAY TO FORM STRING | LEETCODE 1055 | PYTHON GREEDY SOLUTION
9:21
Verifying an Alien Dictionary
14:25
Kevin Naughton Jr.
Рет қаралды 80 М.
LeetCode Decode String Solution Explained - Java
10:52
Nick White
Рет қаралды 58 М.
Meta Coding Interview Question - Group Shifted Strings (LeetCode)
10:33
AlgosWithMichael
Рет қаралды 4,2 М.
КРАХ WINDOWS 19 ИЮЛЯ 2024 | ОБЪЯСНЯЕМ
10:04
Ускоряем ваш TV🚀
0:44
ARTEM_CHIBA
Рет қаралды 418 М.