How to Crack a Google Coding Interview - An Ex-Googler’s Guide

  Рет қаралды 724,683

CS Dojo

CS Dojo

Күн бұрын

Пікірлер: 619
@CSDojo
@CSDojo 7 жыл бұрын
Thanks so much for watching this video, guys! If you're interested in more interview questions like this, I also would recommend my Udemy course, 11 Essential Coding Interview Questions: www.udemy.com/11-essential-coding-interview-questions/?couponCode=HOWTOCRACK
@peterlance6682
@peterlance6682 7 жыл бұрын
Why cant we make a number of the elements in the array. add 1 to it and then take it apart and put it in a an array. [1,2,3,9]==> 1239 1239+1; 1240 loop to separate the digits num%10 put them in an array
@billycl112
@billycl112 7 жыл бұрын
What if the array size is very long, e.g. 1000 ? You won't be able to do that using int/long.
@fixpacifica
@fixpacifica 6 жыл бұрын
Then switch to Java and use BigInteger.
@lawn_mower4941
@lawn_mower4941 6 жыл бұрын
"former " software developer .
@tracyknox515
@tracyknox515 6 жыл бұрын
8
@andrespalermo4743
@andrespalermo4743 3 жыл бұрын
This is literally the first time i understand the code behind a coding interview, that means progress! thank you so much for making it easy to understand
@n2cotine
@n2cotine 2 жыл бұрын
I still do not understand very much 🤧
@ralphchamberlain6580
@ralphchamberlain6580 6 жыл бұрын
CS Dojo. I never thought about the 0-9 concept. Thank you for giving me some knowledge on questions a condition that I wouldn't be aware of.
@rajvigneshh
@rajvigneshh 6 жыл бұрын
Find the length, loop through, multiply by 10^n , 10^n-1 and so on, add one to the number.
@qwarlockz8017
@qwarlockz8017 6 жыл бұрын
I def like how you explain this stuff. You make it VERY clear and it is still very fun to watch. You rock!
@RichardGrable
@RichardGrable 7 жыл бұрын
my approach: def add (arr): res = list(arr) last = len(res) - 1 while True: if res[last] < 9: res[last] += 1 break res[last] = 0 last -= 1 if last < 0: res[0] = 1 res.append(0) break return res
@kalyanchatterjee8003
@kalyanchatterjee8003 5 жыл бұрын
I think the purpose of the video is "how to solve" a technical question in an interview setup and not solving this particular problem. Several people here have commented about other algorithms. I think they are missing the point.
@magnetospin
@magnetospin 6 жыл бұрын
Depending on the language you choose, in the case of 999, your new array may return 1 in the [0] position and random things in the rest.
@turtlefast2396
@turtlefast2396 5 жыл бұрын
Python: Def addOne(set1): Value= (''.join(str(x) for x in set1)*1 Value = int(Value)+1 Value = [int(i) for i in str(value)] Print(Value) addOne([1,2,3,4])
@Zack-dv6rz
@Zack-dv6rz 5 жыл бұрын
Your solution makes sense, I did this in javascript. However my original JS solution involves taking the array of numbers, joining it into a string, parse inting it, adding the value 1, turning the value ack into a string, splitting it then mapping it running parse int individually on each element. I mean it works, and the reason for mapping at the end is he says they're integers which to me means they'll be number values and not strings or any other type of primitive value.
@treyquattro
@treyquattro 7 жыл бұрын
I haven't seen anyone point out yet that in the final instance if carry is 1 and you allocate a new array then you destroy the previous result. Creating a new array doesn't automatically copy the previous contents. Either you need to grow the resultant array if your runtime supports it, then move everything down one, or you need to allocate a new array, copy result[] into it at offset 1 then assign the new array reference or pointer to result (and delete the previous result vector if your language doesn't automatically garbage collect).
@yassineghariani1505
@yassineghariani1505 7 жыл бұрын
Since we only add one, the only case we have to grow the array is when the given array is 999 so we don't need to copy the result because we know the result will be 1 and 0 0 0 (Depending on garbage collector you will need to initialize array with 0s)
@treyquattro
@treyquattro 7 жыл бұрын
The point is that you can't always rely on the new array contents being initialized. He doesn't specify this and it's supposed to be pseudo-code. If you coded this in C you'd get garbage in your newly allocated array.
@babolat435
@babolat435 6 жыл бұрын
Trey Quattro good point! But I don’t think he knows C
@andrewhughes459
@andrewhughes459 6 жыл бұрын
He says in the video we are assuming the language initializes the array to 0s by default
@larry5911
@larry5911 6 жыл бұрын
That would be an assumption you'd tell your interviewer.
@noahsnoeks9193
@noahsnoeks9193 5 жыл бұрын
You can improve the loop by changing if total statement to "if total != 10: carry=0;break;" Cause once the carry is zero it cannot become 1 thus the rest is unnecessary if you copy the original array instead of making a new one
@bwandesky
@bwandesky 2 жыл бұрын
Interesting suggestion.
@jaacobb123
@jaacobb123 6 жыл бұрын
Concatenate each element in the array, turning it into an integer, add one, turn it back into an array. Of course implementing that code is another story, for me at least.
@ajitzote6103
@ajitzote6103 5 жыл бұрын
Time limit exceeded will be the error
@blackrack2008
@blackrack2008 4 жыл бұрын
Depends on the max size of the given array, that should be the first question you ask imo. But if the size is small enough to not exceed the integer limit, this would be my go-to solution as well because of it's simplicity, we essentially don't have to do anything that would be error-prone.
4 жыл бұрын
Few things 1. I also thought about convert to int, increase, and convert back to array, AFAIK there is no number limit in Python 2. Even if we will do it with arrays, you might use funct divmod in one step 3. I found out your solution something between Java and Python, but more Java because you are using fixed arrays. If you use Python and variable arrays, you can simply pop last element, add it to the end of a new array, and then adding next numbers incremented by possible carry to the beginning, whole logic would be much simpler
@the7esla989
@the7esla989 2 жыл бұрын
He’s more proficient in JAVA looks like
@onuberonly7846
@onuberonly7846 7 жыл бұрын
don't ask unnecessary question, We like to see coders think for themselves and show initiative. A "good" interviewer will let you know if you are going in the wrong direction anyway. Use words like " I would do this..." if it's the wrong method the interviewer will let you know what they are intent on seeing. project confidence in your solution (even if it's wrong), don't be timid and unsure of yourself if you are stuck say something, speak up! How many times have we hired people who do great on the technical interview but turn out not to be dedicated. Dedication is the most desirable quality, not skill !
@Vamp898
@Vamp898 7 жыл бұрын
What do you expect from that kind of interview. Someone who is dedicated might not solve the problem in the interview, but later because he is dedicated enough to work on it and improve. He might even solve more complicated issues due to his dedication. Someone with enough experience or who have a lot of fun with puzzles, sorting algorithms or math in general will solve this, might even ask the right questions but will not be dedicated and never solve something else. So instead of just changing the quiz often enough until you find something that shows that he is not dedicated, just check if he is dedicated in the first place, no matter if he can solve the issue or not. There are no stupid humans, you can learn and do everything if you are dedicated enough so dont check "can he do it", check "can he learn it"
@fixpacifica
@fixpacifica 6 жыл бұрын
I've never done a Google interview so don't know specifically what they're looking for, but in another "How to do Google technical interview" video, the person from Google said that the person being interviewed is expected to ask questions for clarification, and not to assume anything. Using a String was my first thought, too, but I don't know if that would be considered "too easy." I'd have to ask the person conducting the interview. Not sure what "dedicated" means. I'd say the most important quality of any engineer or programmer is persistence when you run into a problem.
@BrianKrahmer
@BrianKrahmer 6 жыл бұрын
I fully disagree. Obviously, you don't want to ask pointless questions just for the sake of asking questions. However, If I'm interviewing you and you are A) very confident and B) wrong, I'm going to let you finish your wrong implementation, then start asking some very pointed questions. I would much rather have somebody be unsure and vocal about it, so I can guide him back to the correct path, earlier rather than later. Because that's what I want from an engineer, someone who can say "I don't know", rather that somebody who wastes time coding the wrong solution. Also, confidence is often mistaken for arrogance.
@BMartinsGamingExpo
@BMartinsGamingExpo 5 жыл бұрын
@@BrianKrahmer you are correct.
@lazprayogha
@lazprayogha 5 жыл бұрын
Asking questions by actually making statement and let them tell you when you're wrong is the best in this kind of interviews.
@rdias002
@rdias002 7 жыл бұрын
Could I convert the list to a string and then in turn to a number😝 add one then convert to a list
@zachzimmermann5209
@zachzimmermann5209 7 жыл бұрын
Ralph Dias That's exactly what I thought. Seems like it'd be a lot simpler
@SayanPaulcodes
@SayanPaulcodes 7 жыл бұрын
What about 100000 digits
@KeizerSinbad
@KeizerSinbad 7 жыл бұрын
You have to make sure that a "number" data type can hold that many digits. For example, In Java. You would not be able to use int if the array is larger than an integer's max size.
@jeremyheminger6882
@jeremyheminger6882 7 жыл бұрын
You might get a laugh out of the interviewer. While effective. I think it breaks what the question was going for. Also beyond the issue posted above. I think that recasting a variable would take up resources. In a small operation its no biggy but an interviewer is probably looking for optimal performance. Simply being able to write code that does an operation is only half the battle.
@xellos5262
@xellos5262 6 жыл бұрын
If the interviewer would laugh at me for that idea, I'd leave the room and go home. Our goal is to solve problems not to look smart. Giving the proposed problem casting is a valid and simple solution. If 1M digits is a thing my first question would be "Why are there 1 million entries in an array that is a poor way to store data". But then again I'm generally no fan of these types of questions. They're too abstract and lose all meaning. They don't reflect how good of a developer you are.
@adrianvi519
@adrianvi519 7 жыл бұрын
Loop in the video 14:23-14:37 same as 14:38-14:50. Great tutorial.
@jessethouin
@jessethouin 6 жыл бұрын
I thought I was losing my mind!
@ififif31
@ififif31 6 жыл бұрын
We can derive a different algorithmic approach by observing that all we're basically doing is simply adding a one to the first non-nine digit that we observe (from right to left), and changing it to a zero otherwise. Notice also that this approach would make it much more efficient than the solution presented in this video (on average) if we break out of the loop as soon as we find that first non-nine digit. Here is that approach implemented in python: def addOne(array): i = len(array) - 1 while i >= 0: if array[i] != 9: array[i] += 1 return array array[i] = 0 i -= 1 array.insert(0,1) return array
@yoknom
@yoknom 6 жыл бұрын
This is why I watched the whole video, because I though he would mention that in the end to make the code more efficient if the given array is way bigger than these examples.
@mehmetalikarabulut1190
@mehmetalikarabulut1190 6 жыл бұрын
Perfect solution.
@supersaiyan-goku-san
@supersaiyan-goku-san 5 жыл бұрын
Wow! Thanks a lot. I didn't understand the code given in the Video but after seeing this for some time. I got it. Thanks.
@abbc7059
@abbc7059 3 жыл бұрын
in such questions [0, 8,7,6] after adding 1 should return [8, 7,7] not [0, 8,7,7] Means one has to remove 0 from front if of no use. Ex in 0 8 7 7 , 0 has no use.
@Dark.Ventur
@Dark.Ventur 4 жыл бұрын
we can also do that taking each element of array in a string buffer by appending it and then convert that string into an integer and add one to that integer value and last putting each value of that integer to the array. This is my idea , If i am thinking in right direction then please inform me its very kind of you. You are doing great job my friend .
@LeRustal
@LeRustal 5 жыл бұрын
I guess we could optimize it for large arrays/lists, it may depend on the language we are going to use but for some maybe we might avoid doing too many "if connections" I'm thinking of replacing the for loop by a while with two stop conditions It would looks like this: def add(given_array) carry = 1 result = new int[given_array.length] i = 0 while i
@PrashantKumar.GPT3.5
@PrashantKumar.GPT3.5 7 жыл бұрын
Thanks . Always wanted this type of tutorial :-)
@MannyGonzalezReyna
@MannyGonzalezReyna 6 жыл бұрын
I love the way you explain programming, thanks so much!
@MJ-cf9nl
@MJ-cf9nl 5 жыл бұрын
I thought at the beginning his request was to turn the array of integers into an integer number then add 1 at the end. For example: [1, 2, 3, 4] ---> 1235
@prendoso
@prendoso 5 жыл бұрын
I think that would be a good way to approach the problem. Convert to a number, add one, and then convert back. Of course, it would depend on complexity requirements as to whether this was an acceptable solution. It would certainly be simpler than the solution suggested.
@copypaste_pro
@copypaste_pro 6 жыл бұрын
If you came up with the idea of converting it into string -> number -> sum 1 -> convert back, then it might work for some cases but you won't definitely get to work at Google
@ahmadzeed591
@ahmadzeed591 5 жыл бұрын
Big thanks for you and we are looking for more videos
@markonino12
@markonino12 7 жыл бұрын
lol I don't know WHY I sat through this entire video but dude.. applause. u coders live in a whole other world man
@nnmartin94
@nnmartin94 6 жыл бұрын
What world do you live in? Code is everywhere if you're alive in 2019
@DataHash
@DataHash 5 жыл бұрын
A quick python script using the same solution/simplified logic: def addArray(a): carry = 1 for i in range(len(a)-1,-1,-1): n = (a[i] + carry) % 10 carry = (a[i] + carry) // 10 a[i] = n if carry: a.insert(0,1) return a ------------------------------- To Test: print(addArray([1,3,2,4])) print(addArray([9,9,9,9])) print(addArray([1,9,9]))
@tempestuousfabe
@tempestuousfabe 5 жыл бұрын
def addArray(a): return [int(_) for _ in str(int(''.join([str(_) for _ in a]))+1)]
@JacobHo161
@JacobHo161 7 жыл бұрын
Thank you for your contributions. This helps a lot for my coming interview
@paolocabaleiro
@paolocabaleiro 7 жыл бұрын
Very nice interview question. I wanted to share my implementation of the problem (Python 3) def add_one(array): if not next(filter(lambda x: x != 9, array), None): # All elements of the array are equal to 9 return [1] + [0] * len(array) for i in range(1, len(array) + 1): if array[-i] != 9: return array[:-i] + [array[-i] + 1] + [0] * (i - 1)
@IzzyIkigai
@IzzyIkigai 6 жыл бұрын
it surprises me how people argue over "can't you just cast it to int?" and the counter question is "what if the array is longer than MAX_INT?" - if it actually is, you won't have access to array.len in most languages you might choose. Like a C++ std::size_t limit - which is usually the biggest integer the system can handle. Not to mention that question is unrealistic - even assuming super efficient memory structures that would blow your memory away if it only runs on a single computer - it'd be 2^64 nibbles(smallest possible size for 0-10), which would come down to 6 exibyte just for the data, not even the data structures. So actual question should be what if the the array's size is >20? If it's less, go ahead, cast it to an unsigned int, add one, cast it back to an array. Probably in most high lvl langs much faster doing a check on the array.len and casting it than doing 20 iterations of a loop just to find that you need to create a new object... In the end this is a basic computer science problem for scientific calculations with larger-than-max_int-numbers, where you have to reinvent the wheel unless your language already supports integer types that are large than what your hardware can handle. Python does this and it uses a very similar approach for the data structure with a struct carrying a long and another struct inside that has an array and an integer for length(see PEP 0237).
@footlongchen
@footlongchen 7 жыл бұрын
love your videos man keep it up!
@cosmosnomad
@cosmosnomad 5 жыл бұрын
I've seen a few of your videos before and I'm learning python for data science(I have math and statistical training) so when I started watching this video I was thinking of your other interview videos and was wondering how hard these questions are supposed to be(to someone with formal CS training and someone without it), but this video explains it in so many words. I've seen the time complexity stuff, which I imagine once you take the time to understand isn't that difficult. I've seen there's quite a lot of problem solving involved, which seems to involve understanding of what the question asks, data structures(?), and perhaps some mathematical things I take for granted. So given that it doesn't seem too bad, to me anyway. I just need to make sure I understand data structures and time complexity first and foremost. Although I may learn other stuff while learning that. Personally it's just a matter of finding the time but I'll be grateful once I do understand it. For a CS major, I imagine this *should* all be a given but the logical look at the high level discussion might cause some problems possibly, hence the reason for these videos.
@manosriram
@manosriram 6 жыл бұрын
This Worked for me In Python: a2=[] a1=[] def magic(a1): s = map(str,a1) s = ''.join(s) s = int(s) return s s = int(input()) for t in range(s): a = int(input()) a1.append(a) res = magic(a1) res1 = res + 1 res2 = str(res1) for t in range(len(res2)): a2.append(res2[t]) print(a2)
@rarebit4430
@rarebit4430 Жыл бұрын
Yeahhh, I'm thinking of starting a career as a web developer, and at the moment, I know absolutely nothing about coding. Watching this has just made me feel like I need to be a rocket scientist to pass an interview.
@bobinwobbin4094
@bobinwobbin4094 3 жыл бұрын
def upList(obj): for a in range(len(obj)-1,-1,-1): if obj[a] != 9: obj[a] = obj[a] + 1 break else: obj[a] = 0 else: return [1] + obj return obj
@BrighterWay
@BrighterWay 5 жыл бұрын
You are just doing great hope you will recover fast ...
@promamukherjee5874
@promamukherjee5874 5 жыл бұрын
I just love that cute little fluffy penguin stuffie ❤️🐧
@heh2k
@heh2k 3 жыл бұрын
Also, you can snoop the first digit, if it's != 9, the array size can be the same.
@ericoschmitt
@ericoschmitt 2 жыл бұрын
Isn't it simpler to concatenate each element to a string, convert to integer, add 1 to it, then into string again, and for each element in the string push a new element into an empty array? This one covers any cases be it 123, 199, or 999.
@NathanHeskia
@NathanHeskia 7 жыл бұрын
python w/o converting to string: def add_one(digits): n = len(digits) - 1 return reduce(lambda a, b : a + b[1]*10**(n-b[0]), enumerate(digits), 0) + 1
@johncarlos2849
@johncarlos2849 7 жыл бұрын
thanks man! u're doing great for people like me.
@cryptoseries3259
@cryptoseries3259 6 жыл бұрын
You are genius man...I wonder how you managed to logically use those array to write code like that. I hope I will be able to logically write code like that one day. I’m still learning Python though. Started 3 days ago. My goal is to invest 2hrs everyday to learn it for 1 year..Hopefully I will good like you one day. I’m 38 years old though😁... so far, I have learnt variables and values, functions.. integer, float, operator string, list, casting, swapping , . The more I’m learning it; the more is getting tough. Lol..
@AMNevesGaming
@AMNevesGaming 6 жыл бұрын
You could optimize and end the loop when carry = 0
@NikhilDhiman
@NikhilDhiman 5 жыл бұрын
I feel, you don't have to create a new array, until entry is like 9999 .. Else you can modify the current array and stop whenever you get carry=0 and return the actual array.
@santhoshreddy1992
@santhoshreddy1992 3 жыл бұрын
Jus append new element .. No need of new array
@catalicos
@catalicos 6 жыл бұрын
Interesting. A JS one liner for the given arr = [1,3,2,4], could be: ((parseInt(arr.join('')) + 1) + '').split('')
@Bobxchen333
@Bobxchen333 5 жыл бұрын
but what if the array is 30 digits in length, do you think you can still do parseInt ?
@foqy_rao
@foqy_rao 6 жыл бұрын
In python 3 we can do this easily by : print(list(str(int("".join(c))+1)))
@souihernajah5430
@souihernajah5430 4 жыл бұрын
the point is to implement an algorithmic solution at the end it's an interview to test your problem-solving skills not your knowledge of a specific language
@KouriiRaiko
@KouriiRaiko 5 жыл бұрын
I think it would be easier to reverse the array, then search for the first number that isn't 9. Add one to it and return. If you can't find any number that isn't 9 in the reversed array, just turn all the elements to 0 and add a 1 at the beginning. It's still O(n) on both accounts.
@shivaa3ps177
@shivaa3ps177 4 жыл бұрын
Thanks for explaining that in detail. But a small question.... Why only "Ex-Google" or FANG employees make these videos? I mean... Does Google or FANG ban you from making such videos or monetize your social media?
@cbwavy
@cbwavy 4 жыл бұрын
I'm debating whether a job at Google is worth the pain of prepping for the interview. I feel like part of the reason the interview is so hard is to discourage people like me, who are scared, from even trying. Which I guess makes sense, but sucks and drains life energy from me altogether. For the record, this problem isn't difficult, doing it on the spot with people watching you is the difficult part.
@felnyr3448
@felnyr3448 5 жыл бұрын
In python 3: arr = [1,3,4,5,9] def addOne(arr): newArr = str(arr) for x in newArr: if x == "[" or x =="]" or x == "," or x ==" ": newArr = newArr.replace(x, "") return list(str(int(newArr) + 1)) print(addOne(arr))
@wooh88
@wooh88 3 жыл бұрын
Good video. Thanks for sharing and walk through the interview process.
@powder77777
@powder77777 6 жыл бұрын
I think max array size is max integer. So you can convert array into integer with math and add 1. Then conversation integer back to array.
@sshum00
@sshum00 7 жыл бұрын
This is how I would approach it: def add_one(arr): carry_over = 1 result = [] for element in arr[::-1]: sum = element + carry_over result.append(sum%10) carry_over = sum//10 if carry_over: result.append(1) return result[::-1]
@socketseven3434
@socketseven3434 7 жыл бұрын
this is how i would : (lambda a:map(int,str(int(''.join(map(str,a)))+1)))([9,9,9])
@vladislavkudelin9820
@vladislavkudelin9820 7 жыл бұрын
I think converting it to int and adding 1 is NOT what's required here. I am afraid, one must struggle with implementing the addition the way they tech it in school ("the column method" with "carry" etc). Because if not, the "problem" is too simple for a Google interview (and here is my solution which is much shorter and cleaner than your solution): int("".join([str(x) for x in a])) + 1 # given a = [1,2,3] or a =[9,1,9,9] or a = [9,9,9] or whatever ...
@vladislavkudelin9820
@vladislavkudelin9820 7 жыл бұрын
And the "An Ex-Googler" must be ashamed of himself in any case : 15 (!) minutes of blah-blah-blah for such a trivial task.
@vwwvwwwvwwwvwwvvwwvw
@vwwvwwwvwwwvwwvvwwvw 7 жыл бұрын
Ken, something bad must have happened while you copied Vlad's code. You're right though that it's not correct because it doesn't return the int in "array form".
@jiansenxmu
@jiansenxmu 6 жыл бұрын
SpaceChuppy This is the best.
@bmiquelin
@bmiquelin 7 жыл бұрын
I made it int two ways (C#): 1: Loop in the vector and check the number change. 2: Parse the vector into an int32, add 1, then convert back. (CAN GET OVERFLOW. Changing only Int32 to Int64 or UInt64 WILL NOT WORK) The first one ran at approx 2 million times in 5 seconds. The second one ran approx 6 million times in 5 seconds. private static int[] add_one1(int[] given_array) { given_array[given_array.Length - 1] ++; for (int i = given_array.Length-1; i >= 0; i--) { if (given_array[i] == 10) { given_array[i] = 0; if (i > 0) given_array[i - 1]++; else { given_array = new int[given_array.Length + 1]; given_array[0] = 1; } } } return given_array; } private static int[] add_one2(int[] given_array) { Int32 num = 1; for(int i = 0; i
@prathapmaturi8061
@prathapmaturi8061 7 жыл бұрын
Thanks, clean explanation.
@МохамедРусланович
@МохамедРусланович 6 жыл бұрын
hey people , where can i find more of these interview tasks?? i need it so much
@connergoldberg
@connergoldberg 7 жыл бұрын
This is how I would solve it. I'd take the array and convert it over to a string iteratively concatenating each integer as a char. Then I would take the string representation of the integer and attempt to parse it as an integer (if it fails, it's obviously not a valid integer and will trigger an exception). I would then add one to the integer. I would then use modulo on the integer to break apart each digit iteratively into a new array to be returned. That to me is the simplest solution.. so I'm not sure if they would accept that xD..I wrote an example of how I'd tackle it in c# below. Unsure how performant it is though..hmmm probably would be better off just using a for loop on the original array. public int[] add_one(int[] digits) { string integer = string.Join("", digits).Replace("-",""); //We don't allow negatives try{int result = int.Parse(integer) + 1;} catch(Exception ex) { throw new Exception("Error: Unable to parse integer array");} var resultList = new List(); for (; result != 0; result /= 10) resultList.Add(result % 10); var resultArray = resultList.Reverse().ToArray(); return resultArray; }
@kaysong1494
@kaysong1494 5 жыл бұрын
Pretty good, but why you do not choose a bigger board :)
@gta-im8zt
@gta-im8zt 4 жыл бұрын
🤣
@pouria2728
@pouria2728 4 жыл бұрын
I'd do it in *3 easy* steps!!: 1. *convert that do number* 2. *do the math* 3. *convert it back to list* and that's Done! No one seen that 😉14:36
@itorres008
@itorres008 5 жыл бұрын
At the beginning of the interview you should ask the guy if he wants to optimize execution speed, elegance, code readability or least time to code it. :-)
@vbnm193
@vbnm193 6 жыл бұрын
Wouldn't a link list be easier because it easy to traverse the link list and change the data. If it is the 999 case, just add a new node.
@jefftspang
@jefftspang 5 жыл бұрын
I know the point of the question is to demonstrate, but i see some comments saying to convert to string. Convert it into number directly will be faster //convert to integer (only works on positive numbers) int number=0; for(int x=0;x=0) { int m = number % 10; newArray[y] = m; number=number/10; y--; } return newArray;
@codeking1120
@codeking1120 7 жыл бұрын
sir please make video on how to calculate time and space complexity
@chrisv7892
@chrisv7892 6 жыл бұрын
here is a good interview question there are 88000 people working at google total, less then half of those function as programmers. If google hires 10,000 people a year and 2.5 million people have reviewed the how to work at google youtube video. What are your chance of getting hired. Please use a data structure to show your answer.
@mob_abominator1868
@mob_abominator1868 6 жыл бұрын
Data is insufficient.
@cherifayman4397
@cherifayman4397 Жыл бұрын
def decomp_array(given_array): index = len(given_array) - 1 new_array = given_array while index != -1: if new_array[index] < 9: new_array[index] += 1 carry = 0 break else: new_array[index] = 0 index -= 1 carry = 1 if carry == 1: print([1]+new_array) else: print(new_array) decomp_array([9,9,9,9]) i dont know but i think this work well
@大盗江南
@大盗江南 5 жыл бұрын
u r such an amazing IT guy... thx so much
@ednara9689
@ednara9689 2 жыл бұрын
JS: const addArray= (arr => { let newarr = (+arr.join('')) + 1 let finarr = Array.from(String(newarr), Number) return finarr }) addArray([1,2,4,9]) I think this is faster than iterating over the arrray multiple times.
@biomorphic
@biomorphic 6 жыл бұрын
Do an explode of the array to generate a string, then cast the string to an integer, add one, then cast back to a string and from string to array. 4 line of code max. I would have never hired you with the solution you have shown in this video.
@drivgest
@drivgest 7 жыл бұрын
hi coding jojo.. nice content... in what setting does google give interviews...? is it a panel... or 1 on 1...? on by skype....? ang how long does the interview last....? can you make a vid on that..?
@migoiegdul6532
@migoiegdul6532 5 жыл бұрын
JavaScript: const question = arr => (parseInt(arr.join('')) + 1).toString().split(''); console.log(question([1,2,3,9]));
@thelonearchitect
@thelonearchitect 5 жыл бұрын
You are using 4 linear functions, so you end up with O(4n) while the original solution, less elegant, is just O(n). As of space complexity, you are converting to a string of n characters and back into an array of n entries which makes it O(3n), against a O(n) solution again.
@marshallkapfudza1686
@marshallkapfudza1686 5 жыл бұрын
Nice solution. I think you should convert your answer to be the array of numbers by adding .map(Number) const question = arr => (parseInt(arr.join('')) + 1).toString().split('').map(Number)
@NeeleshSalpe
@NeeleshSalpe 6 жыл бұрын
Simple python code def add(a, add_num): carry = add_num result = list() for digit in reversed(a): result_num = digit + carry if int(result_num / 10) >= 1: carry = int(result_num / 10) one_digit_num = result_num % 10 result.insert(0, one_digit_num) else: carry = 0 result.insert(0, result_num) if carry > 0: result.insert(0, carry) return [digit for digit in result]
@ARUNTOM
@ARUNTOM 6 жыл бұрын
I wrote a one-liner in python 3. ls=[9,9,9] #input intls=[int(x) for x in list(str(eval("".join([str(x) for x in ls]))+1))] #output
@matheburg
@matheburg 5 жыл бұрын
Good example that one-liners are not always good solutions (in regard of performance and readability).
@lailai6402
@lailai6402 6 жыл бұрын
Find last number that is not nine and add one to it, zeroing the numbers as you go. If it doesn't exist, add a 1 in front of the list.
@swapnilchopade8158
@swapnilchopade8158 6 жыл бұрын
I think i have better solution.The time and space complexity is better.also the ans is in form of list For best case time complexity is 1 and for worst case time complexity is n for i in range(len(list)): If list[-i-1]==9: list[-i-1]=0 else: list[-i-1]=list[-i-1] + 1 break If i==len(list): list.insert(-100000,1) print(list)
@thegreatsilence1081
@thegreatsilence1081 5 жыл бұрын
Awesome 👍 elaboration Could u make more videos...
@mauriciocortazar9604
@mauriciocortazar9604 6 жыл бұрын
what do you think of the next approach O(n): def add_one(given_array): if not given_array: return [] if given_array[-1] == 9: if len(given_array) == 1: return [1, 0] return add_one(given_array[:-1]) + [0] else: given_array[-1] += 1 return given_array arr = [9,9,9] print(add_one(arr))
@bamless95
@bamless95 4 жыл бұрын
The people that say you can solve this by converting it to a string, then a number, adding one and reversing the process are missing the point. What if you do not have an integer type that can store the converted value? Then you get an overflow and the algorithm doesn't work anymore. You can argue that you can use an arbitrary sized integer like BigInteger in Java, but think carefully about that. How do you think BigInteger.add is implemented? With an algorithm similiar to this one (probably working in binary though). That's basically solving the problem with a library that solves it with extra steps, not that good of an answer to a question designed to challenge your algorithmic skills.
@simonshu3435
@simonshu3435 6 жыл бұрын
I would do it with 5 loc in Python in this way: from functools import reduce def fn(x, y): return x * 10 + y L=[9,9,9] print((reduce(fn, L))+1)
@0xW0L0L0
@0xW0L0L0 7 жыл бұрын
One line in Python 3: print(list(str(int("".join(map(str, set)))+1))) # where the variable "set" is the array # it prints a list of string, it can be mapped to int # to be just like the original array but I didn't find it necessary
@yassineghariani1505
@yassineghariani1505 7 жыл бұрын
This won't work if the number exceeds the integer type limit.
@0xW0L0L0
@0xW0L0L0 7 жыл бұрын
Yassine Ghariani That is not true. Have you tested it before commenting? Python 3 does not have an int limit size (: Here you go: print(int('893274569823456892374235234523452345456745674565')) If that was true, the INT casting here would have removed part of the number, but when we cast it again to string (print will do that) it has the original number, so it prints: 893274569823456892374235234523452345456745674565
@spiderous
@spiderous 6 жыл бұрын
Marcelo Ely Ok, but what about other languages? Your solution should be universal.
@raymondfellers3801
@raymondfellers3801 6 жыл бұрын
This IS universal. Python runs just about everywhere and this is one of the reasons: It makes many problems tedious to code fairly easy solve and easy to test. As a hiring manager I would expect this answer or similar in just about any language because many have this capability within the language or popular frameworks. And if in the interview I was looking for fluency in a language that did not allow one to solve the problem with string to int to string conversions readily, I would expect a senior eng., before diving into the algorithm, to point out that the problem can be solved by looping over the array elements and tracking the carry but if simplicity and expediency are important we can solve it with strings. When I am interviewing candidates, I am not only looking for the ability to solve problems, but I also want engineers that have the experience and wisdom to pick the right tools (languages) and craft solutions that not only work, but are easy for others to understand and test. For real work on large coding projects, the string solution is what you want because there are no loops or conditionals to check. It just works and is easy to confirm that is works by just looking at the code, no hand tracing required.
@ShuskiCross
@ShuskiCross 6 жыл бұрын
In c# it would be (set being the array): (int.Parse(string.Join("", set)) + 1).ToString().Select(x => (int)Char.GetNumericValue(x)).ToArray(); Whether that is the optimal way I don't really know. I just know this one works.
@donnygroulx4543
@donnygroulx4543 6 жыл бұрын
Well my python might be a bit rusty, but if you coded that in Java you would have to copy the array contents of the results array into a new array (reaults2). If you don't, re initializing the array wipes the contents of your original copy of the array and your new result would be [1, 0,0,0]. Having said that, I would probably have just iterated the array to form the integer, added 1 and then exploded a new array on a toString of the int. Thanks for sharing. I hope all google interviews couple be this easy :)
@havalopez
@havalopez 3 жыл бұрын
I think while this is probably the most practical solution, I think it violates the spirit of the question. The interviewer wants to see your thought process in developing an algorithm to handle adding the numbers.
@TheOriginalComments
@TheOriginalComments 7 жыл бұрын
You bring great value.
@darshanpatil6892
@darshanpatil6892 3 жыл бұрын
```python arr = list(map(int, input().split())) a = 1 for ind, ele in enumerate(reversed(arr)): a += ele*10**ind print(list(int(i) for i in str(a))) ``` I don't know if I'm wrong!!! I'm learning from here!
@stockhutzo
@stockhutzo 5 жыл бұрын
With Python i solved this problem in 5 minutes, with C, it took over half an hour, slower to write, but faster to execute, so there is my C version: #include #include //function for printing result void print_result(int res[], int size, char isTen){ int len; if(isTen) len = size / sizeof(int); else len = (size / sizeof(int)) - 1; for(int i = 0; i < len; i++) printf("%d ", res[i]); printf(" "); } int main(int argc, char *argv[]){ //get length of arg int len = strlen(argv[1]); //initialize array (with lenght + 1 to avoid recreating array in case input is 99, 999 etc.) int res[len + 1]; for(int i = 0; i < len; i++){ res[i] = (int) argv[1][i] - '0'; } //adding 1 to last element res[len - 1]++; //looping from last element to first int i = len; while(i > 0){ if(res[i] == 10){ res[i] = 0; res[i - 1]++; } i--; } //fixing 99, 999 etc. (with isTen boolean) char isTen = 0; if(res[0] == 10){ res[0] = 1; for(int i = 1; i < (len + 1); i++) res[i] = 0; isTen = 1; } //printing result print_result(res, sizeof(res), isTen); return 0; }
@julianelischer
@julianelischer 5 жыл бұрын
one word for you, pointers..
@stockhutzo
@stockhutzo 5 жыл бұрын
In Python it took just 5-10 minutes (without spaghetti code one-liners or list->string->int->list conversion), but later i'm going to try with a lower-level language like C, and i guess it's going to be more difficult, anyway that's my Python code: #!/usr/bin/python3 from sys import argv #parsing array from args res = [int(x) for x in argv[1]] #adding 1 to last element res[-1] += 1 #looping from last element to first i = (len(res) - 1) while i > 0: if res[i] == 10: res[i] = 0 res[i - 1] += 1 i -= 1 #fixing 99, 999 etc. if res[0] == 10: res= [1] + [0 for x in res] #printing result print(res)
@yacinechettabravenclaw2832
@yacinechettabravenclaw2832 4 жыл бұрын
I loved it, thanks. Ps: you could've used break in: Else: carry=0; break ;
@gunnu4u
@gunnu4u 5 жыл бұрын
In JavaScript you can do: function addOne(arr) { var str = arr.join(''); str = (Number.parseInt(str) +1) + ""; arr = str.split(''); return arr; }
@ortizstlBTNE
@ortizstlBTNE 6 жыл бұрын
Ruby solution def add_one(given_array) given_array = (given_array.join('').to_i)+1 given_array = given_array.to_s.split('') given_array end puts add_one([1,2,9,9])
@roniegh
@roniegh 7 жыл бұрын
This is how I would approach it in Ruby: def add_one_to_ary(_array) _index = -1 _array.dup.tap do |_result| while _result[_index] == 9 _result[_index] = 0 _index -= 1 end if _result[_index] _result[_index] += 1 else _result.unshift(1) end end end add_one_to_ary([9, 9, 9]) > [1, 0, 0, 0]
@yeshwanthchowdary
@yeshwanthchowdary 5 жыл бұрын
In scripting languages, array length is not fixed. Therefore, in JavaScript we can do parseInt(givenArray.join(''))+1
@AdamSafadi
@AdamSafadi 5 жыл бұрын
It doesn't return an array but only the total
@joshualim8471
@joshualim8471 5 жыл бұрын
@@AdamSafadi then make it array after you did this. Correct me if i am wrong. 🙂
@AdamSafadi
@AdamSafadi 5 жыл бұрын
@@joshualim8471that's right ((parseInt([9,9,9].join(''))+1).toString()).split("")
@ev.c6
@ev.c6 2 жыл бұрын
You can solve this problem with three lines as seen bellow. I will assume the list is small enough not to concatenate with str(), otherwise a forloop will be needed to extract the numbers. import re a = [1, 3, 2, 4] r = re.sub(r"\[|\]|,| ", "", str(a)) s = int(r) + 1
@DemenciaSenil0
@DemenciaSenil0 6 жыл бұрын
join -> convert to int -> add 1 -> split
@bikasgupta4454
@bikasgupta4454 5 жыл бұрын
Great course preview sir but i don't have money to buy that course but thanku
@RonitGhosh
@RonitGhosh 6 жыл бұрын
the easier way would have been to convert the array into a number, add 1 and then convert it back to an array
@Andr3ymzq
@Andr3ymzq 6 жыл бұрын
let's say you have given array : [1 , 2 , 3 ,4 ] . why not form an integer like int number = 1000*array[0]+100*array[1]+10*array[2] + array[3] ; Afterward you could easily append 1 that that integer number and conversion to array would be the reverse process .
@Tony-Lin
@Tony-Lin 7 жыл бұрын
intern season got this guy so many subscribers
@Yotanido
@Yotanido 7 жыл бұрын
add_one = reverse . toList . (+1) . toInt . reverse where toInt [] = 0 toInt (x:xs) = x + toInt (map (*10) xs) toList i | i < 10 = [i] toList i = i `mod` 10 : toList (i `div` 10) By no means efficient, but fairly straight-forward. (This is in Haskell)
@moritzschmidt6791
@moritzschmidt6791 5 жыл бұрын
My Solution working with powers of the decimal system: public static void main(String[] args) { int[] number = {1,2,3,4}; int result = 0; for(int i=number.length ;i>0 ; i--) { int multiplier = (int) Math.pow(10, i-1); result += multiplier*number[(i-number.length) * -1]; } result+= 1; System.out.println(result); }
@jimnewton4534
@jimnewton4534 6 жыл бұрын
Adding 1 is a special case. you could 1) check for all 9s and return 1000..., else 2) look from the right and find the first non-9, and increment it. right?
@ContortionistIX
@ContortionistIX 5 жыл бұрын
Isn't the line "if sum == 10: carry = 1" redundant, as it's already 1? btw, here's my slightly different solution in python: def addOne(input): result = input result[-1] += 1 for i in range(len(input) - 1, 0, -1): if input[i] == 10: result[i - 1] += 1 result[i] = 0 if result[0] == 10: result = [0 for i in range((len(result) + 1))] result[0] = 1 return result
@panjc8543
@panjc8543 5 жыл бұрын
i like your solution, its simply bcuz u only work with 2 variables
@adarshchaudhary5362
@adarshchaudhary5362 6 жыл бұрын
The solution I came up with is converting it to number by multiplying each array element with corrosponding power of 10 then adding one and they converting it to array by dividing by power of 10
@gubl3e
@gubl3e 5 жыл бұрын
Same here
5 Problem Solving Tips for Cracking Coding Interview Questions
19:12
ССЫЛКА НА ИГРУ В КОММЕНТАХ #shorts
0:36
Паша Осадчий
Рет қаралды 8 МЛН
How to have fun with a child 🤣 Food wrap frame! #shorts
0:21
BadaBOOM!
Рет қаралды 17 МЛН
She wanted to set me up #shorts by Tsuriki Show
0:56
Tsuriki Show
Рет қаралды 8 МЛН
How I Failed the Google Coding Interview (and lessons I learned)
14:24
Google Coding Interview - Universal Value Tree Problem
17:11
CS Dojo
Рет қаралды 181 М.
Google Interview Experience | Accepted... then Rejected
17:23
Keep On Coding
Рет қаралды 398 М.
I Asked Googlers How To Get Hired
9:44
Namanh Kapur
Рет қаралды 1,7 МЛН
Amazon Coding Interview Question - Recursive Staircase Problem
20:01
Advice from the Top 1% of Software Engineers
10:21
Kevin Naughton Jr.
Рет қаралды 3,4 МЛН
How To Get Into Google - 6 Tips That'll Get You In (as a software engineer)
14:42
Whiteboard Coding Interviews: 6 Steps to Solve Any Problem
15:18
Fullstack Academy
Рет қаралды 382 М.
Google Coding Interview With A Competitive Programmer
54:17
Clément Mihailescu
Рет қаралды 2,5 МЛН
How to: Work at Google - Example Coding/Engineering Interview
24:02
Life at Google
Рет қаралды 7 МЛН
ССЫЛКА НА ИГРУ В КОММЕНТАХ #shorts
0:36
Паша Осадчий
Рет қаралды 8 МЛН