Google Coding Interview Question and Answer #1: First Recurring Character

  Рет қаралды 2,022,768

CS Dojo

CS Dojo

Күн бұрын

Find the first recurring character in the given string!
A variation of this problem: find the first NON-recurring character. This variation problem and many others are covered in my Udemy course, 11 Essential Coding Interview Questions: www.udemy.com/11-essential-co...
(You'll get a discount through the above link.)

Пікірлер: 1 700
@CSDojo
@CSDojo 5 жыл бұрын
Hi guys! I actually made a mistake in my first solution.. sorry. The first recurring character in ABBA should be B, and not A. Also, I should've used a set in my second solution. The time complexity is the same either way, though.
@ACarbonellBeceiro
@ACarbonellBeceiro 5 жыл бұрын
You don't loop, but query it directly with a given key, in this case the char itself. Example: hashTable.has('A') // true or false if the table has that key or: hashTable.get('A') != null // true or false if the table has that key I did show 2 variations because it can vary from one language to another. The .has() method is just a helper that some implementations offer. The second example can cause problems if we actually want to store null values, but for this case works fine. A hashtable has a constant access time, O(1), so the overall time complexity does not increment.
@kumakun3861
@kumakun3861 5 жыл бұрын
too late over half a million ppl watched lmaooo
@IceQub3
@IceQub3 5 жыл бұрын
Lol I just thought about that before resuming the video, my solution tho is using a int with size of n bits. Then I check if the bit in the place of the character is on or off. If it on return the number. If it off turn it on. As that more efficient in memory (the hash can be stored in a register). If I want to redefine the problem to result A in a ABBA case my solution is failing because I can't know the order of the characters in the input string. In such case using a table won't help ether because hash table don't keep order of inserion ether. I don't have a real good simple solution for that problem right now. As the efficient way I am thinking about is creating the hash in a way that every recurring characters are marked with a on bit. Then looking for the first 'on' character in the string. I find my solution not simple because it has those 2 steps that I need to repeat...
@cyhlau
@cyhlau 5 жыл бұрын
For "first solution" he is referring to the O(n^2) solution that scan each character and try to find a match in the remaining characters. Using that solution, the input "ABBA" would return 'A', but the correct answer should be 'B', according to the question definition.
@fahadjaved9855
@fahadjaved9855 5 жыл бұрын
CS Dojo Assuming the characters can only be ASCII (or any character encoding with a constant number of characters), your second solution has an O(1) runtime complexity. Not O(n) because your string can be 256000 characters long but you will see a repeated character after 256.
@johannesvahlkvist
@johannesvahlkvist 5 жыл бұрын
"we're going to use pseudo code to explain this code" > uses python LOL
@asthamalhotra2345
@asthamalhotra2345 5 жыл бұрын
I was thinking the same😁
@algoseekee
@algoseekee 5 жыл бұрын
Probably it was a subtle trolling 😉
@HandledToaster2
@HandledToaster2 5 жыл бұрын
LOL
@play005517
@play005517 5 жыл бұрын
isn't Python just a runnable pseudo code?
@HandledToaster2
@HandledToaster2 5 жыл бұрын
@@play005517 no its real code, Reddit works on Python. It's just weird
@ilustrado7291
@ilustrado7291 6 жыл бұрын
What if I just wanna sweep the floor and clean the toilets?
@LouisNgatale
@LouisNgatale 6 жыл бұрын
lmao
@SanthoshKaitheri
@SanthoshKaitheri 6 жыл бұрын
For that, u dont need to fuck around a Coding Video.
@WakeUpSmellTheCoffee
@WakeUpSmellTheCoffee 6 жыл бұрын
Plot twist: floor sweepers and toilet cleaners at Google are robots programmed by these coders. Our job prospects just got lowered! 🤪
@YoungOrbital
@YoungOrbital 6 жыл бұрын
Classic miss direction and you fell for it, the only purpose for this video is to asses their future janitor if he can work out if he has cleaned a toilet twice during his shift.
@adarshinginshetty484
@adarshinginshetty484 6 жыл бұрын
Watch a toilet cleaning tutorial.that will help u more than a coding video.
@sompamalakar
@sompamalakar 6 жыл бұрын
Instead of using a HashMap, you could use a bit vector as the hash map. Set the bit of the character in the bit vector while you encounter it and if the bit is already set, thats the first recurring character.
@firefoxmetzger9063
@firefoxmetzger9063 6 жыл бұрын
Actually the run time for the hashing variant is O(const) (and O(n) for small lists). We will find a double character within the first k+1 elements of the list where k is the number of valid characters. If the string is encoded in say UTF-8 our charset has 8 bit, thus we will inevitably find a repeating character after 256 elements and can ignore the remaining list. If our charset is even shorter (say only A-Z [note the capital]) as in this case, we only consider the first 27 characters. This number is independent of the lists actual size, thus it will work in constant time for long lists. The same goes for the first variant which is O(n^2), we can prune comparing against characters that are more then charset+1 away from the start and will find one within the first charset + 1 characters. This will result in a runtime of O( [charset + 1]^2 ) which is lower then O(n^2) for big lists. Which variant is faster then becomes interesting, because we might be able to further optimize via multicore processing or SIMD ...
@MoRasheed
@MoRasheed 6 жыл бұрын
I'm an IT graduate (computer networks) but this comment section makes me reconsider my life decisions
@alibaba8266
@alibaba8266 6 жыл бұрын
why ?
@rodrigoogirdor774
@rodrigoogirdor774 6 жыл бұрын
Modi Rasheed why?😂
@WakeUpSmellTheCoffee
@WakeUpSmellTheCoffee 6 жыл бұрын
Cuz coding is more fun than IT. I’ve done both. Just my opinion :p.
@justinjohn93
@justinjohn93 6 жыл бұрын
Same here
@deecoder4497
@deecoder4497 5 жыл бұрын
Same here bro
@marcom2092
@marcom2092 6 жыл бұрын
Came into the comments section not knowing anything about this subject and now I feel dumb
@sanketsony8143
@sanketsony8143 6 жыл бұрын
Marco M lol! then why this video came into your feeds in the first place?
@Loser-ow6ye
@Loser-ow6ye 6 жыл бұрын
Marco M sameeee
@Dalendrion
@Dalendrion 6 жыл бұрын
Why? Obviously you're not going to know anything about a subject you haven't studied. :D If you've studied it extensively and you still don't understand it, _then_ you may feel dumb about it. And even then, so what? Feeling dumb simply means you just found out that you have something to learn. Feeling dumb has nothing to do with being dumb. :)
@vaishnavi5070
@vaishnavi5070 6 жыл бұрын
Dalendrion u know the last line of ur cmnt is like inception ending scene for me. what i mean is i didnt get it
@Dalendrion
@Dalendrion 6 жыл бұрын
vaishnavi Our feelings are often illusions. They are emotions. And emotions aren't logical. So these feelings often give us an incorrect idea about reality. You may feel dumb even if you aren't. You may feel smart even if you aren't.
@lvlichaelly
@lvlichaelly 6 жыл бұрын
I have gone through google phone interview twice before and to be honest it's never as easy of this.
@tigerrx7
@tigerrx7 4 жыл бұрын
Fundamentally, if you understand Data Structures and Algorithms you can solve this one. This is why those two classes are ALWAYS recommended (required even) before any elaborate code building. Great vid to reinforce the fundamentals
@jeremyingraham9344
@jeremyingraham9344 6 жыл бұрын
Wouldn't just a set work better? It's O(1) lookup and requires less space.
@WendyWangMusic
@WendyWangMusic 6 жыл бұрын
Would hash set be better? In hash table you are storing another column count, which uses more space... In hash set, you only need to check whether the element is in the set. If it is already in the set, then you return this element right away...
@CSDojo
@CSDojo 6 жыл бұрын
Yeah using hash set would be another option. Same space complexity though.
@asphix
@asphix 6 жыл бұрын
CS Dojo its the same space complexity but hashset in this case is certainly a better option. I guess you can use the hash table and if interviewer asks for space optimization you can suggest a hashset with minimal code change
@_sudosu
@_sudosu 6 жыл бұрын
It hardly depends on the language. For instance, in Java HashMap is used internally in the HashSet collection thus it does not bring any memory optimization.
@khaledsaleh4238
@khaledsaleh4238 6 жыл бұрын
Agree , HashSet is better in my opinion too!. Thanks for your suggestion , Wendy!
@dafemartdafemart4020
@dafemartdafemart4020 6 жыл бұрын
what's the complexity of a look up in your hash table?
@JannisAdmek
@JannisAdmek 6 жыл бұрын
after seeing your video I made a short python script with two functions, the first using the good, the second the poor algorithm. I made a list with 10000 random, not repeating characters and at the end AA. Here are the results: good: (using a set and going through ones) 0.0789 sec bad: 9.46 seconds! Nice video, thanks for enlightening
@Michael-bt8fn
@Michael-bt8fn 6 жыл бұрын
A rather simple operation with Time O(length of string) and space O (1) is using bit operations. Just define a mask 0, loop through the characters get bit of mask at location char-'A'. If 0 is gotten, set to 1. And continue looping, if 1, return char
@GoHomeAndGetYourShinebox
@GoHomeAndGetYourShinebox 6 жыл бұрын
Interviewer asks question: *Me* : Ummm can I go to the toilet and does it have wifi?
@agnesmortey7266
@agnesmortey7266 4 жыл бұрын
Go home and get your shine boxes jumped poor village training Lord37899 Henry
@mistermomo2904
@mistermomo2904 3 жыл бұрын
@@agnesmortey7266 Agnes Morty has issued an insult Lord Vyron 12937 Mark ii; the shoes are shined and feet are in the boxes
@dotanoob466
@dotanoob466 5 жыл бұрын
This is too easy for a google question i feel
@dkarbaev
@dkarbaev 5 жыл бұрын
dota noob probably a warm-up question. I was told that their interviewer might ask a couple of simple questions before getting for a hard one.
@kharinskiyalexey7409
@kharinskiyalexey7409 5 жыл бұрын
If I were a google interviewer, I would ask after that: "Can you solve it with O(1) space?". Not so easy anymore?))
@Abdulmajeed-sy1us
@Abdulmajeed-sy1us 5 жыл бұрын
@@kharinskiyalexey7409 Without checking n characters we can't conclude so they can't ask like that
@kharinskiyalexey7409
@kharinskiyalexey7409 5 жыл бұрын
@@Abdulmajeed-sy1usof course you have to check you, go on :) but with O(1) space
@calmsh0t
@calmsh0t 5 жыл бұрын
Mhhh not necessarily. I don't think that the problems itself are unsolvable at these companies, I believe that they are more looking for how you solve it and if you can get to the uber-smart approach they are expecting (tough for me, since I mostly work after the pattern "make it work, optimize it later")
@user-ov5nd1fb7s
@user-ov5nd1fb7s 5 жыл бұрын
In your assessment of the time complexity, you should add the time that it takes to actually create a hashtable and insert the values. That would have increased memory usage as well. Depending on your time and memory constraints, you have to use different approaches.
@NeverCodeAlone
@NeverCodeAlone 5 жыл бұрын
I love this explaining style and videos - now you are on our inspiration channel!!
@Zir0KZN
@Zir0KZN 6 жыл бұрын
Thank you! It was pretty simple to solve. Wait for the harder ones :)
@mathewdempsey16
@mathewdempsey16 5 жыл бұрын
Well that was easy, using a hash table was literally the first thing that popped into my mind
@Thatguy-ru3hw
@Thatguy-ru3hw 6 жыл бұрын
So thorough unlike most channels. Thank you very much earned a subscribe!
@TNTsundar
@TNTsundar 5 жыл бұрын
You could use a bitmap to mark the seen characters and when the same character is seen the next time, you could return that character simply. This way you save space as well by not tracking the character and the count in a dictionary/hash table. For example, for 96 printable ASCII characters including special characters, you would need only 12 bytes to mark different characters that are seen as we pass each character. Since we are interested only in the first reoccurring character we don’t need more than 12 bytes. We mark each character from the string using a lookup table and set the corresponding bit in the bitmap. We can have different ranges for special characters and normal characters in the bitmap and mark appropriately. The first reoccurring character can be found when we try to set the bit which is already set. This way we don’t use a lot of space as well as the time complexity is at minimum (which is similar to the solution presented in the video).
@codybarscott6280
@codybarscott6280 5 жыл бұрын
It's actually a very good exercise. Thank you. I think it would be something like this in Java (though my first approach was the naive solution, I agree with using a Map instead) import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MainApp { public static void main(String[] args) { //the subject String String someString = "ABCDEFGAD"; //split subject String to an array String[] someStringCharArray = someString.split(""); //the Map to fill in with individual character and count per character Map map = new HashMap(); //start looping through comparing and counting for(int i=0; i 1){ System.out.println(o); } } } }
@arpanm9652
@arpanm9652 6 жыл бұрын
I got the exact same question in my college exams.. and I wrote the first solution. Guess what - I got the FULL marks😐😂😂😋😋
@JPNSynster
@JPNSynster 5 жыл бұрын
I love your channel I hope you return again soon. I really love the python series, you have such a great way of teaching.
@bennydcunha1514
@bennydcunha1514 6 жыл бұрын
the idea of an array is perfect
@jatinlalwani9459
@jatinlalwani9459 6 жыл бұрын
The two solutions that you mentioned (O(n^2) and O(n)) produce different results for the string ABBA. Now I am confused which one is first recurring char in ABBA, A or B. If it is B then your second solution would work properly (Set would be better though). But if it is A then we can use dictionary like you did with chars as keys and respective counts as values. We need to traverse the complete string to complete the dictionary then we could start traversing the string again and for every char we would refer dictionary for its count. Once we reach a char for which count is >1, return. Time complexity - O(n). Space - O(1). Any better solution?
@avinashkhare1341
@avinashkhare1341 6 жыл бұрын
I think the second solution is wrong.
@wwxk123
@wwxk123 6 жыл бұрын
his brute solution is wrong; like you suggested ABBA will return A when in fact ABBA should return B. For second method, I don't think it matters whether you use hashset/map or even an array. What does matter is that the space is not O(n) but rather O(1) since there are limited number of alphabets (52 if case sensitive, 26 otherwise).
@pepajimenez8376
@pepajimenez8376 6 жыл бұрын
Exactly what I was going to comment! The problem is not properly defined, is the first recurring character the first one to appear twice or the first one in the sequence that repeats? His solution only works in the first case.
@pedant9134
@pedant9134 6 жыл бұрын
exactly what I was confused about
@TheAuxLux
@TheAuxLux 6 жыл бұрын
I agree that 2nd solution gives correct result, since in ABBA, A recuring in 4th spot, and B is recurring in 3rd. However I not quite agree we have O(n) in second solution. Sure we go only forward the string, but we iterate each table row every char. Sure, most languages are making this for us in lower level, yet still are doing.
@Jorde
@Jorde 5 жыл бұрын
You could also create an array of length 26 in which you insert the ascii code to int and increment the position and then when the index is equal to 2 stop and convert the index to the position getting the character
@vigneshviggu8417
@vigneshviggu8417 2 жыл бұрын
Became your subscriber. Your sessions are awesome dude
@ridiculoustoysss
@ridiculoustoysss 4 жыл бұрын
in real work environment, it will be like: 1. google 'find first recurring character' 2. click into stackoverflow, copy, done
@Francefire
@Francefire 4 жыл бұрын
🤣🤣🤣
@engineergirl6869
@engineergirl6869 4 жыл бұрын
accurate!!!! lol
@vaishaligupta1360
@vaishaligupta1360 6 жыл бұрын
We can actually terminate it just when the count of any of the characters become 2 since we are concerned about only the first recurring character.
@ryuaan
@ryuaan 3 жыл бұрын
The hash table is def more elegant and better time complexity. My first attempt in c++ was of a double for loop O(n^2), 2 array chars, & 1 basic char. One array char to hold the letters, another array char to assign & store duplicates found by a third plain char holding current indexed letter.
@AlokKumar-jh8wp
@AlokKumar-jh8wp 6 жыл бұрын
Thankyou csdojo for explaining it in a great way you are doing a great job for us.
@g_455
@g_455 6 жыл бұрын
The counts of the character is of no use, so why not use a Set (like hashset) instead.
@kkppccdd
@kkppccdd 6 жыл бұрын
Ganesh _ the complexity of hashset and hashtable is equivalent. Here it supposed the time complexity of ‘ if e in counts ‘ is 1. If the size of counts may grow large, it needs to optimize ‘if e in counts’.
@rajeshdansena
@rajeshdansena 6 жыл бұрын
Agree. Better optimized memory.
@x-yl
@x-yl 6 жыл бұрын
Some performance numbers in python (running the method on string.printable 10000 times): List - 1.8005362025424931 seconds Dictionary - 0.4816858277563984 seconds Set - 0.2586124478794257 seconds Looks like a set would have been the best choice.
@wozhendeaa
@wozhendeaa 6 жыл бұрын
Using hashset is still the same memory complexity. They are the same. You can use an array instead if you worry about the nonexistent memory overhead
@kalebbruwer
@kalebbruwer 6 жыл бұрын
It is useful for the problem he mentioned at the end.
@TheRahul9191
@TheRahul9191 4 жыл бұрын
Another approch is to use Set data structures. Start adding char in set through iteration. Check lenght after each value appended in set, if length does not change then return that char. This is in O(n) time complexity and good space complexity over HashTable.
@AvinashSharma-fr5lh
@AvinashSharma-fr5lh Жыл бұрын
set element insertion takes logN time so the complexity will be NlogN and not N
@denysivanov3364
@denysivanov3364 Жыл бұрын
@@AvinashSharma-fr5lh set is slower than dict?
@AvinashSharma-fr5lh
@AvinashSharma-fr5lh Жыл бұрын
@@denysivanov3364 I think it is.
@princedavidbuduru4242
@princedavidbuduru4242 6 жыл бұрын
very helpful and great teaching thank you so much for impacting my life! and i cant wait to start learning code with you!!
@radhekrishanrathod9001
@radhekrishanrathod9001 5 жыл бұрын
Hi I am in last year of my CS graduation.Videos are really helpful.😀
@ironrose6
@ironrose6 3 жыл бұрын
My thought was simply to iterate through the array and for each element, check the length of a set before and after adding the element to that set. If the length increases, that's the first time the element has occurred in the array. If the length stays the same, the element was already in the set and therefore it's the first recurring element.
@grantmartin2002
@grantmartin2002 3 жыл бұрын
most add functions actually return a boolean value for if the set was changed or not (at least in java). So all you would really have to do is if(!set.add(char)){ return char}
@ironrose6
@ironrose6 3 жыл бұрын
@@grantmartin2002 Interesting! Unfortunately, it doesn't work that way in python- it just returns "None". But I didn't know that about java!
@mrankushtechnical
@mrankushtechnical 6 жыл бұрын
What were the questions asked to u ??
@hitzcritz
@hitzcritz 6 жыл бұрын
I don't think you are allowed to reveal the questions a company asks you for an interview.
@nimisidiv9244
@nimisidiv9244 6 жыл бұрын
You are just being known as a whistle blower is career ending in tech
@aakash9475
@aakash9475 6 жыл бұрын
I think they are pretty basic questions. And you always can share interview questions.
@invictuz4803
@invictuz4803 6 жыл бұрын
lmao interview questions are not some trade secret. Say you don't even get the job, how can they enforce that you don't talk about your interview. Also, it's not like there's a public database of whistle blowers.
@allisonosullivan6095
@allisonosullivan6095 6 жыл бұрын
mrankushtechnical dog shall ask would he pick up phone bring washing over babe babe yes or no
@ajr_almeida
@ajr_almeida 6 жыл бұрын
Bro, you're awesome. You explanation is very easy to understand. Thank you!
@techtitbits
@techtitbits 5 жыл бұрын
You make coding simple. Thanks
@tariqganem1109
@tariqganem1109 3 жыл бұрын
him : asking him a very simple ques me: apply dfs on array of trees
@adamgomaev6968
@adamgomaev6968 4 жыл бұрын
I just started to learn programming at university and I think it`s too early for this kind of videos for me. lol
@sunrise8263
@sunrise8263 6 жыл бұрын
Congratulations, You took clear water and muddied it.
@shree203
@shree203 6 жыл бұрын
Dude. Ur videos are so freaking clean and simple... I like it...😍
@prabhur764
@prabhur764 6 жыл бұрын
hey ,its very easy man.
@lokakshabm2612
@lokakshabm2612 5 жыл бұрын
Even if we don't have any recurring characters in the first 26 characters of the string, the 27th character will be recurring, since we have only 26 alphabets (assuming the string contains only alphabets). So time complexity is O(26), which can also be written as O(1). Even if the string can contain all ASCII characters, it can still be considered O(1) according to me.
@tornes
@tornes 5 жыл бұрын
That's a deeper understanding of the problem, nice
@sangramjitchakraborty7845
@sangramjitchakraborty7845 5 жыл бұрын
But you still have to traverse the whole thing to find the element that is recurring. And if the input is smaller than 26 you can't use the pigeonhole principle.
@lokakshabm2612
@lokakshabm2612 5 жыл бұрын
@@sangramjitchakraborty7845 As soon as you find the first recurring character you can exit the for loop. The first recurring character can't come after 27th position, because for it to do so all the positions before it must contain different characters, which is not possible since only 26 characters are possible. Hence 27th position or lower positions must contain at least one recurring character which will be the first recurring character.
@lokakshabm2612
@lokakshabm2612 5 жыл бұрын
@@tornes Thank you
@sangramjitchakraborty7845
@sangramjitchakraborty7845 5 жыл бұрын
Ahh. I see what you mean. Thats a great approach.
@KGcodes
@KGcodes 4 жыл бұрын
Pretty simple but good to nail this down as it could be a building block to harder problems.
@MsThekiller02
@MsThekiller02 3 жыл бұрын
I just started uni and got the answer right, didn't think about the naive way at all. I come up with a good enough solution and then I optimize it. If you shoot for the stars right away, you'll struggle a lot because you're gonna get stuck on the details and you won't get anything from that. My high school computer science teacher used to say "you can't build a skyscraper all at once, start with the foundations, then build your way up"
@Luckpart1
@Luckpart1 5 жыл бұрын
A simple hashing to 26 bits should work to avoid using extra space as well.
@KirinDave
@KirinDave 5 жыл бұрын
I like this and I was reaching for it in my head too, but I think to properly answer strings like "ADDA" with an 'A' you wouldn't be able to reduce this to a range/popcount problem.
@jorgeromero3422
@jorgeromero3422 6 жыл бұрын
I'm so proud I solved it by my own
@agnieszkarutkowska8244
@agnieszkarutkowska8244 3 жыл бұрын
Me too :)
@lajti4376
@lajti4376 3 жыл бұрын
xd
@pantagry
@pantagry 5 жыл бұрын
you could also use hashset and check only for length after adding to it, so if count of elements unchanged - you have duplicate
@rahulsethione
@rahulsethione 5 жыл бұрын
I’d use a Set. Over the loop if set.has(str[i]) then return it. Else set.add(str[i]).
@akshadk7
@akshadk7 6 жыл бұрын
I guess it would not be much harder for me to crack their interview if they ask such questions
@GacemAyoub
@GacemAyoub 6 жыл бұрын
for (i from 0 to n - 1) { character = input_string[ i ] counts[character] = 1 if (counts.size() < i + 1) return character } return none This variation take advantage of the unicity of Hash keys
@akarshy
@akarshy 6 жыл бұрын
Ayoub Gacem this is a great solution that is actually O(n)
@vanessahayes6471
@vanessahayes6471 6 жыл бұрын
Thank god I found this channel better late than never, I guess
@prasannalakshmi1081
@prasannalakshmi1081 6 жыл бұрын
Ur videos are so impressive and interesting and make everyone enjoy the fruit of programming
@pranavbhat29
@pranavbhat29 6 жыл бұрын
I thought the first recurring character is the one which has a frequency greater than one in the string and it has the least index among all such possible characters. Like in this particular algorithm, a string "bcaabd" would return "a" since "a" repeats for the first time, but I thought asked me to return "b" instead ( since among the characters which repeat in the string, b occurs for the first time in the string. )
@jrajesh11
@jrajesh11 6 жыл бұрын
Yes, that is what I think is more accurate as it takes the whole word into account, and not just an incomplete word.
@hdwe1756
@hdwe1756 6 жыл бұрын
I was just thinking about adding them to an array and checking if they were in it....
@louiswouters71
@louiswouters71 6 жыл бұрын
I don't get it. They are already in a string, so you could just start at the 2nd level and see if its in the first position. Then continue to take the n-th letter and check it with the first n-1 letters. It uses the same amount of comparisons as his 'correct' solution.
@yashsoni501
@yashsoni501 6 жыл бұрын
Louis, both the solutions are correct but the second one is better than the first one as it takes much lesser comparisons. Your method uses same number of comparisons as his first method which is n(n-1)/2...
@LoveWillB4U
@LoveWillB4U 6 жыл бұрын
Checking if something exists in an array takes at best O(1), on average O(n/2) -> O(n), and at worst O(n) comparison. Checking something if it is in a hashmap/hashset takes at best O(1), on average O(1), at worst O(n). So adding an item into an array and then checking if it is in an array is O(n^2), which is what we want to avoid. Use a hashmap/hashset when you don't care about the order it gets added into the hashmap/hashset.
@hdwe1756
@hdwe1756 6 жыл бұрын
Leighton Lee Thanks, I get it now.
@RomanSteiner_xD
@RomanSteiner_xD 6 жыл бұрын
Leighton Lee, assuming there are only uppercase English letters (it seems so), you could use an array of 26 booleans and use the current char as index (its ASCII value minus that of 'A'). That way it's always O(1) for the lookup because you don't actually have to search for anything. If you're short on memory you could even use a 4byte bitmask in the same way :3
@BetoEats
@BetoEats 4 жыл бұрын
Great video, I enjoy refreshing my knowledge with some sample problem 👍
@ManishGupta-wb2wc
@ManishGupta-wb2wc 6 жыл бұрын
Good job . Need more videos like this
@saadakhtar2000
@saadakhtar2000 5 жыл бұрын
I am student of First Semester of B.S(CS). I literally pused it and thought a rough algorithm and I made it on my FIRST try C++ ! :) Really really happy to realize my hidden skills :-D
@sagan666
@sagan666 5 жыл бұрын
UNIX solved all of this over 40 years ago. You can man sort, sed, awk, grep et al.
@DotSimLtd
@DotSimLtd 6 жыл бұрын
A quicker way is to simply use a list where the letter is stored at an index in the list or array lookup. If the string was large you could even speed up using heuristics such as a coarse sort.
@holonaut
@holonaut 6 жыл бұрын
Storing the letter as an index in a list/array/dictionary (call it whatever) is exactly what he does in the second solution, isn't it?
@DotSimLtd
@DotSimLtd 6 жыл бұрын
Except an array is much quicker access than a dictionary.
@dhruvsingh3066
@dhruvsingh3066 6 жыл бұрын
bro pls keep on uploading such questions from Google , i wanna learn more
@jydk37
@jydk37 6 жыл бұрын
I would design a neural network to figure it out while I ate a snack
@azztereris
@azztereris 6 жыл бұрын
jydk37 wtf? hahaha
@vedant6633
@vedant6633 6 жыл бұрын
Lol
@fikkitchen
@fikkitchen 6 жыл бұрын
xD
@vedant6633
@vedant6633 6 жыл бұрын
You're selected ~google interviewer
@SanderMFC872
@SanderMFC872 6 жыл бұрын
Trying random solutions until you get the answer is bad. But if you do it fast enough it's called machine learning.
@MarcusAseth
@MarcusAseth 6 жыл бұрын
Hey I've answered that right, so I'm now I Google employee? Nice! :D
@JakubSK
@JakubSK 6 жыл бұрын
This is insanely simple. I'm kind of surprised this was a Google question. Wow.
@vivilee7290
@vivilee7290 6 жыл бұрын
I like your video so much. It's clear and easy to learn.
@VLS-Why
@VLS-Why 6 жыл бұрын
If you can use JavaScript couldn't you run through your array once and compare indexOf with lastIndexOf and return the first value where they are not the same?
@LoubrielJayneberg
@LoubrielJayneberg 6 жыл бұрын
It would have to parse the array every time you use indexOf and lastindexOf. Not the most efficient solution.
@mikheilchkheidze1629
@mikheilchkheidze1629 6 жыл бұрын
It is not very efficient to make people read long names either
@blasttrash
@blasttrash 6 жыл бұрын
And it is also not very efficient to make people read unpronounceable names either. ...Lets start the bashing. :P Juz kiddin though. Happy coding. :)
@TheFreakinProgrammer
@TheFreakinProgrammer 5 жыл бұрын
Will that work for string "ABBA"? No
@zuko655
@zuko655 5 жыл бұрын
@@TheFreakinProgrammer with this it does: function findRecurrence(str) { for(let i = 0; i < str.length - 1; i++) { let char = str.charAt(i); if(str.indexOf(char) !== str.lastIndexOf(char)) return char; } return null; }
@marcushines4172
@marcushines4172 6 жыл бұрын
Just use a set, bro. HashMap is the wrong tool for this job but the idea behind your solution is correct. We just don't care how many times we've seen a char, only that we've seen it before. Good job though!
@marcushines4172
@marcushines4172 6 жыл бұрын
...A Set has constant time lookup, and yes it has a hashing function which gives us the O(1) time complexity. I understand the task is about the underlying algorithms, I was simply pointing out that there is a better tool to accomplish this task . But....I guess when all you have is a hammer, everything looks like a nail.
@marcushines4172
@marcushines4172 6 жыл бұрын
...also you should delete your comment about the quadratic time complexity, since you are in fact wrong. That way, people in the future will not be confused by your incorrect reasoning.
@henriksundt7148
@henriksundt7148 6 жыл бұрын
I guess this is a general coding interview, not python specific. In that case the candidate does the right thing (like in the video), to explain what actually happens, independent of what the language provides.
@cipherxen2
@cipherxen2 6 жыл бұрын
Marcus Hines In java hashset internally uses hashmap. And hashset don't always give constant time lookup, it depends upon hashing function.
@marcushines4172
@marcushines4172 6 жыл бұрын
The developers at Oracle seem to be pretty smart. I'm sure their implementation of a hash function for the HashMap/HashSet is fine, so the comment about "depends upon the hashing function" is really meaningless. You all are making a big deal about nothing, lol. I simply stated that he can accomplish the same result, without having to count the occurrences of the characters.
@nikitafulzele6099
@nikitafulzele6099 5 жыл бұрын
Keep going your explanation is understandable
@koushikn3016
@koushikn3016 3 жыл бұрын
Simple and Soothing
@SreeragNairisawesome
@SreeragNairisawesome 6 жыл бұрын
why not use a simple bit vector of size 26 (total no. of characters) , keep marking the corresponding rows '1' as you find unique characters and when you try to mark an already marked row, return the corresponding character.
@illiap3628
@illiap3628 6 жыл бұрын
It does not say anywhere that the string only contains uppercase English alphabet letters, so your algorithm might not work.
@SreeragNairisawesome
@SreeragNairisawesome 6 жыл бұрын
Illia Potapchuk if that's the case ,then a 52 bit vector will suffice..... I don't see any problems now.
@illiap3628
@illiap3628 6 жыл бұрын
What about other symbols or numbers?
@SreeragNairisawesome
@SreeragNairisawesome 6 жыл бұрын
Illia Potapchuk well ,I originally assumed characters as only letters.... and the video also mentions only alphabets.
@hisjojo6312
@hisjojo6312 6 жыл бұрын
Or maybe 256 size for ASCII code
@CutTheRope1
@CutTheRope1 6 жыл бұрын
In the second method, wouldn't the O-notation not be O(n) since in addition to checking the String you are also checking the created set for every character?
@MoJo01
@MoJo01 2 жыл бұрын
Less processing but more memory. Guess it depends on what hardware you want to utilize. But usually small if the string is anticipate to be small, then processing is valued over memory I assume. But the instruction won't be repeated, I think that's what the O is about, not overall complexity, but instruction repetition. Oh, just noticed your comment is 3 years ago. Well, cheers.
@jacobmiller7175
@jacobmiller7175 2 жыл бұрын
@@MoJo01 well im glad you mentioned that, i had that thought as well so I am glad you left a reply. Ill have to look into it more, but now i no where to start so cheers to you!
@nikitafulzele6099
@nikitafulzele6099 5 жыл бұрын
I understand all what you have explained thank you
@maxfan6035
@maxfan6035 2 жыл бұрын
This *simple* problem can be a foundation to solve some appearingly complex problems. Thanks
@Bazoozehindizzle88
@Bazoozehindizzle88 6 жыл бұрын
Don't these two solutions do different things? Given the string "ABCBDA", solution 1 would return "A", whereas solution 2 would return "B", right?
@pk062
@pk062 6 жыл бұрын
Rowan Hatherley You are right
@sukeshkumard6064
@sukeshkumard6064 6 жыл бұрын
Rowan Hatherley, you absolutely right. I was so much confused doing this many times and came to know that this twp solutions gives two different answers.
@jatinlalwani9459
@jatinlalwani9459 6 жыл бұрын
Correct! I think he needs to clarify what is first recurring char. In a string ABBA, the first recurring char is A or B?
@nealpatel7696
@nealpatel7696 6 жыл бұрын
It's B. Basically, just look for the character you see twice first. Since you return after the first recurring character (B), the second, third, ..., recurring characters don't matter. ABCA returns A because A is the only recurring character, therefore, the first recurring character. BCABA returns B because B is the first recurring character. Given ABCBDA, it would return B since it's the first recurring character.
@shanugarg8428
@shanugarg8428 4 жыл бұрын
Hey guys Checkout this Google interview problem that's solved with 4 different approaches from scratch to code really quick at : kzbin.info/www/bejne/q5SwdXuLr8Z7bJI
@Seanbo88
@Seanbo88 6 жыл бұрын
Me before 2:19 "Oh, hey, maybe I can understand coding. Me after 2:19 "Nope"
@PsyfirX
@PsyfirX 6 жыл бұрын
Seanbo88 I wouldn't worry, the guy in the video doesn't understand coding either.
@Mikt25
@Mikt25 3 жыл бұрын
Watch some of his or other people's videos on Big O notation. It's not as hard and intimidating as it looks. CS Dojo's explanation of it is one of the better ones.
@swaraj8769
@swaraj8769 5 жыл бұрын
I think a linear solution is possible by using map in c++. I extract each character from the string and increment the count. If I get a count greater than 1, I print that character. Then in a visited array, I set the attribute to true so that I don't print the same character again.
@jamaajair393
@jamaajair393 Жыл бұрын
Yes your code is more clearly and simple to get it. Thank you
@TonyThomas01
@TonyThomas01 5 жыл бұрын
From what I see, most interview questions (specially on phone and online) are a coversion from a O(n^2) to O(n). And when you have it, hashmaps - there you go! :) Saved my ass last Friday (before I saw this video though).
@juarezsotelo
@juarezsotelo 6 жыл бұрын
This is my solution in java 8: private static Character findFirstRecurring(String letter){ char[] l = letter.toCharArray(); Set list = new HashSet(); for (char c: l) { if (!list.add(c)) { return c; } } return null; }
@tsetsenmendsaikhan252
@tsetsenmendsaikhan252 6 жыл бұрын
Congrats, We're hiring you as Security Guard.
@rodrigoogirdor774
@rodrigoogirdor774 6 жыл бұрын
Tsetsen Mendsaikhan omg i am dying 😂😂
@darellarocho5729
@darellarocho5729 6 жыл бұрын
Lmao!
@Unbreak00
@Unbreak00 6 жыл бұрын
very nice bro
@bubba6755
@bubba6755 6 жыл бұрын
Very helpful,thanks!
@ezequielcervantes3925
@ezequielcervantes3925 5 жыл бұрын
It should be mentioned that the linear time solution also incurred a linear space complexity.
@sefkannnn2085
@sefkannnn2085 5 жыл бұрын
This guy looks from macdanuru drive thru.
@zuko655
@zuko655 5 жыл бұрын
A JavaScript solution: function findRecurrence(str) { //convert string to array const arr = str.split(""); //construct new set from array and check if the size is the same if(new Set(arr).size === arr.length) return null; //loop through array and use slice method to extract elements starting at current index +1 so that the current index is not on the new array //check if this new array contains the current element, return it if so for(let i = 0; i < arr.length - 1; i++) { if(arr.slice(i+1).indexOf(arr[i]) !== -1) return arr[i]; } }
@Thiago-jm7gr
@Thiago-jm7gr 5 жыл бұрын
Good job. By performance purpose you can replace arr.slice() with arr.indexOf(arr[i], i + 1). Slice function creates a useless array, which turns the algorithm a bit slow I created this gist to demonstrate my tests! Check this out: gist.github.com/thiago-tallison/36b3e826a856f9ffaa1cdd09dcf95265
@GrandpappyLuke
@GrandpappyLuke 5 жыл бұрын
IndexOf makes this solution n^2 which is just as bad as checking every pair.
@nguyenhoanglong420
@nguyenhoanglong420 4 жыл бұрын
Wow this coding interview question is really awsome :3
@sophiaatn5339
@sophiaatn5339 5 жыл бұрын
Thanks so much for this
@BarksApp
@BarksApp 4 жыл бұрын
First question I ask on an interview... What sound does an owl make?
@AaronBrand
@AaronBrand 3 жыл бұрын
If you've heard one in flight, they're actually pretty quiet. Like a gentle "whoosh" sound.
@kablouserful
@kablouserful 6 жыл бұрын
"write some pseudo code" *writes python* XD classic
@milew81
@milew81 6 жыл бұрын
Thanks! Great video
@chinmayhundekari
@chinmayhundekari 5 жыл бұрын
In your code, you need to add the elements to a hash table. You have to include the time taken for that.
@bobsanchez6646
@bobsanchez6646 6 жыл бұрын
Your naïve solution returns a different answer than your final solution for the case "abba." Therefore one of your solutions isn't a solution at all.
@ningdi6545
@ningdi6545 6 жыл бұрын
idk for abba we should return a or b?
@hjdeheer
@hjdeheer 6 жыл бұрын
b . Its the first recurring character
@RandomGuy-df1oy
@RandomGuy-df1oy 4 жыл бұрын
public String findFirstRecurring(char[] array) { String answer = null; for(int i=array.length - 1; i>0; i--) { for(int j=i-1; j>0; j--) { if(array[i] == array[j]) { answer = "" + array[j]; } } } return answer; } Thats the naïve solution I guess.
@thewayofbeauty5731
@thewayofbeauty5731 4 жыл бұрын
So there is no naive solution for this problem, basically.
@shanugarg8428
@shanugarg8428 4 жыл бұрын
Hey guys Checkout this Google interview problem that's solved with 4 different approaches from scratch to code really quick at : kzbin.info/www/bejne/q5SwdXuLr8Z7bJI
@MrGamingPigeon
@MrGamingPigeon 5 жыл бұрын
Console.writeline("pls hire me senpai");
@LukaCekovic
@LukaCekovic 6 жыл бұрын
Great video, subbed immediately!
@pankajarmo129
@pankajarmo129 4 жыл бұрын
The answer would be different in "naive" and hash table method if the string is DBCAAB. In naive method it would return B while in other it will return A.
@GuyMichaely
@GuyMichaely 6 жыл бұрын
Aren't both solutions O(n^2)? For the second solution, the programming language will have to compare char against each item in the list, won't it? That would make it O(n^2) if i'm not mistaken. Can anyone confirm/deny?
@manfredzalud7914
@manfredzalud7914 2 жыл бұрын
I thought so as well. But the comparison of the chars will only take a constant amount of time, because there is a finite number of possible characters
@peterhayman
@peterhayman 2 жыл бұрын
the 'key' is that unlike arrays hash tables have O(1) lookup time
@yixunnnn
@yixunnnn 6 жыл бұрын
The naive solution does not account for when the there may be an earlier recurrence of another character after the current searched character
@ArnavBarbaad
@ArnavBarbaad 6 жыл бұрын
It does. Since you are starting from the first element, there can't be an earlier recurrence. What you're calling an "earlier recurrence" would actually be the 1st occurrence at some point ealier in the algorithm, and the 2nd occurrence would therefore be caught.
@ArnavBarbaad
@ArnavBarbaad 6 жыл бұрын
Damn didnt think of that. You’re right, however then it depends on the definition of ‘first recurring character’. Does it mean the first character in the string that is repeated or a character in the string to first have two occurrences.
@samwhaleIV
@samwhaleIV 6 жыл бұрын
But when you start from the first character (and the input doesn't change) that doesn't matter. It would work from back to front as well, just so long as you iterate all characters.
@samwhaleIV
@samwhaleIV 6 жыл бұрын
Zuy It means the first, the examples in the video show so.
@Kr2025
@Kr2025 6 жыл бұрын
The first recurring character is still C in B C C B. Since B didnt recurr before C.
@chanchalsinghal5973
@chanchalsinghal5973 5 жыл бұрын
You r great buddy. U r my inspiration , 👍👍👍
@mayankpant1596
@mayankpant1596 2 жыл бұрын
There is also this other approach where you first use merge or quicksort to sort the string character wise, and the ln simply iterate through the array and compare arr[I] and arr[I+1] , if they are equal just return it . Complexity is O(nlogn), but dosent take any extra memory..
5 Problem Solving Tips for Cracking Coding Interview Questions
19:12
How I Failed the Google Coding Interview (and lessons I learned)
14:24
THEY WANTED TO TAKE ALL HIS GOODIES 🍫🥤🍟😂
00:17
OKUNJATA
Рет қаралды 5 МЛН
Super gymnastics 😍🫣
00:15
Lexa_Merin
Рет қаралды 108 МЛН
A pack of chips with a surprise 🤣😍❤️ #demariki
00:14
Demariki
Рет қаралды 55 МЛН
Google Coding Interview With A High School Student
57:24
Clément Mihailescu
Рет қаралды 4 МЛН
Solving A Classic Google Interview Logic Puzzle
9:03
MindYourDecisions
Рет қаралды 8 МЛН
Asking Google Engineers How To Get Hired and Their Salaries
11:05
The Code Skool
Рет қаралды 1,6 МЛН
How to: Work at Google - Example Coding/Engineering Interview
24:02
Life at Google
Рет қаралды 7 МЛН
JavaScript Interview questions everyone gets wrong
6:40
Catherine Li
Рет қаралды 24 М.
Why Good Programmers FAIL Coding Interviews
8:15
Sahil & Sarra
Рет қаралды 337 М.
Coding Interviews Be Like
5:31
Nicholas T.
Рет қаралды 6 МЛН
How I Passed The Google Coding Interviews
18:50
Chris Jereza
Рет қаралды 19 М.
How to NOT Fail a Technical Interview
8:26
Fireship
Рет қаралды 1,3 МЛН
THEY WANTED TO TAKE ALL HIS GOODIES 🍫🥤🍟😂
00:17
OKUNJATA
Рет қаралды 5 МЛН