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
@peterlance66827 жыл бұрын
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
@billycl1127 жыл бұрын
What if the array size is very long, e.g. 1000 ? You won't be able to do that using int/long.
@fixpacifica6 жыл бұрын
Then switch to Java and use BigInteger.
@lawn_mower49416 жыл бұрын
"former " software developer .
@tracyknox5156 жыл бұрын
8
@andrespalermo47433 жыл бұрын
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
@n2cotine2 жыл бұрын
I still do not understand very much 🤧
@ralphchamberlain65806 жыл бұрын
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.
@rajvigneshh6 жыл бұрын
Find the length, loop through, multiply by 10^n , 10^n-1 and so on, add one to the number.
@qwarlockz80176 жыл бұрын
I def like how you explain this stuff. You make it VERY clear and it is still very fun to watch. You rock!
@RichardGrable7 жыл бұрын
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
@kalyanchatterjee80035 жыл бұрын
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.
@magnetospin6 жыл бұрын
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.
@turtlefast23965 жыл бұрын
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-dv6rz5 жыл бұрын
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.
@treyquattro7 жыл бұрын
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).
@yassineghariani15057 жыл бұрын
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)
@treyquattro7 жыл бұрын
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.
@babolat4356 жыл бұрын
Trey Quattro good point! But I don’t think he knows C
@andrewhughes4596 жыл бұрын
He says in the video we are assuming the language initializes the array to 0s by default
@larry59116 жыл бұрын
That would be an assumption you'd tell your interviewer.
@noahsnoeks91935 жыл бұрын
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
@bwandesky2 жыл бұрын
Interesting suggestion.
@jaacobb1236 жыл бұрын
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.
@ajitzote61035 жыл бұрын
Time limit exceeded will be the error
@blackrack20084 жыл бұрын
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
@the7esla9892 жыл бұрын
He’s more proficient in JAVA looks like
@onuberonly78467 жыл бұрын
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 !
@Vamp8987 жыл бұрын
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"
@fixpacifica6 жыл бұрын
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.
@BrianKrahmer6 жыл бұрын
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.
@BMartinsGamingExpo5 жыл бұрын
@@BrianKrahmer you are correct.
@lazprayogha5 жыл бұрын
Asking questions by actually making statement and let them tell you when you're wrong is the best in this kind of interviews.
@rdias0027 жыл бұрын
Could I convert the list to a string and then in turn to a number😝 add one then convert to a list
@zachzimmermann52097 жыл бұрын
Ralph Dias That's exactly what I thought. Seems like it'd be a lot simpler
@SayanPaulcodes7 жыл бұрын
What about 100000 digits
@KeizerSinbad7 жыл бұрын
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.
@jeremyheminger68827 жыл бұрын
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.
@xellos52626 жыл бұрын
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.
@adrianvi5197 жыл бұрын
Loop in the video 14:23-14:37 same as 14:38-14:50. Great tutorial.
@jessethouin6 жыл бұрын
I thought I was losing my mind!
@ififif316 жыл бұрын
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
@yoknom6 жыл бұрын
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.
@mehmetalikarabulut11906 жыл бұрын
Perfect solution.
@supersaiyan-goku-san5 жыл бұрын
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.
@abbc70593 жыл бұрын
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.Ventur4 жыл бұрын
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 .
@LeRustal5 жыл бұрын
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.57 жыл бұрын
Thanks . Always wanted this type of tutorial :-)
@MannyGonzalezReyna6 жыл бұрын
I love the way you explain programming, thanks so much!
@MJ-cf9nl5 жыл бұрын
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
@prendoso5 жыл бұрын
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_pro6 жыл бұрын
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
@ahmadzeed5915 жыл бұрын
Big thanks for you and we are looking for more videos
@markonino127 жыл бұрын
lol I don't know WHY I sat through this entire video but dude.. applause. u coders live in a whole other world man
@nnmartin946 жыл бұрын
What world do you live in? Code is everywhere if you're alive in 2019
@DataHash5 жыл бұрын
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]))
@tempestuousfabe5 жыл бұрын
def addArray(a): return [int(_) for _ in str(int(''.join([str(_) for _ in a]))+1)]
@JacobHo1617 жыл бұрын
Thank you for your contributions. This helps a lot for my coming interview
@paolocabaleiro7 жыл бұрын
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)
@IzzyIkigai6 жыл бұрын
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).
@footlongchen7 жыл бұрын
love your videos man keep it up!
@cosmosnomad5 жыл бұрын
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.
@manosriram6 жыл бұрын
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 Жыл бұрын
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.
@bobinwobbin40943 жыл бұрын
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
@BrighterWay5 жыл бұрын
You are just doing great hope you will recover fast ...
@promamukherjee58745 жыл бұрын
I just love that cute little fluffy penguin stuffie ❤️🐧
@heh2k3 жыл бұрын
Also, you can snoop the first digit, if it's != 9, the array size can be the same.
@ericoschmitt2 жыл бұрын
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.
@NathanHeskia7 жыл бұрын
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
@johncarlos28497 жыл бұрын
thanks man! u're doing great for people like me.
@cryptoseries32596 жыл бұрын
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..
@AMNevesGaming6 жыл бұрын
You could optimize and end the loop when carry = 0
@NikhilDhiman5 жыл бұрын
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.
@santhoshreddy19923 жыл бұрын
Jus append new element .. No need of new array
@catalicos6 жыл бұрын
Interesting. A JS one liner for the given arr = [1,3,2,4], could be: ((parseInt(arr.join('')) + 1) + '').split('')
@Bobxchen3335 жыл бұрын
but what if the array is 30 digits in length, do you think you can still do parseInt ?
@foqy_rao6 жыл бұрын
In python 3 we can do this easily by : print(list(str(int("".join(c))+1)))
@souihernajah54304 жыл бұрын
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
@KouriiRaiko5 жыл бұрын
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.
@shivaa3ps1774 жыл бұрын
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?
@cbwavy4 жыл бұрын
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.
@felnyr34485 жыл бұрын
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))
@wooh883 жыл бұрын
Good video. Thanks for sharing and walk through the interview process.
@powder777776 жыл бұрын
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.
@sshum007 жыл бұрын
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]
@socketseven34347 жыл бұрын
this is how i would : (lambda a:map(int,str(int(''.join(map(str,a)))+1)))([9,9,9])
@vladislavkudelin98207 жыл бұрын
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 ...
@vladislavkudelin98207 жыл бұрын
And the "An Ex-Googler" must be ashamed of himself in any case : 15 (!) minutes of blah-blah-blah for such a trivial task.
@vwwvwwwvwwwvwwvvwwvw7 жыл бұрын
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".
@jiansenxmu6 жыл бұрын
SpaceChuppy This is the best.
@bmiquelin7 жыл бұрын
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
@prathapmaturi80617 жыл бұрын
Thanks, clean explanation.
@МохамедРусланович6 жыл бұрын
hey people , where can i find more of these interview tasks?? i need it so much
@connergoldberg7 жыл бұрын
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; }
@kaysong14945 жыл бұрын
Pretty good, but why you do not choose a bigger board :)
@gta-im8zt4 жыл бұрын
🤣
@pouria27284 жыл бұрын
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
@itorres0085 жыл бұрын
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. :-)
@vbnm1936 жыл бұрын
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.
@jefftspang5 жыл бұрын
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;
@codeking11207 жыл бұрын
sir please make video on how to calculate time and space complexity
@chrisv78926 жыл бұрын
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_abominator18686 жыл бұрын
Data is insufficient.
@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
@ednara96892 жыл бұрын
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.
@biomorphic6 жыл бұрын
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.
@drivgest7 жыл бұрын
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..?
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.
@marshallkapfudza16865 жыл бұрын
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)
@NeeleshSalpe6 жыл бұрын
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]
@ARUNTOM6 жыл бұрын
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
@matheburg5 жыл бұрын
Good example that one-liners are not always good solutions (in regard of performance and readability).
@lailai64026 жыл бұрын
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.
@swapnilchopade81586 жыл бұрын
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)
@thegreatsilence10815 жыл бұрын
Awesome 👍 elaboration Could u make more videos...
@mauriciocortazar96046 жыл бұрын
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))
@bamless954 жыл бұрын
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.
@simonshu34356 жыл бұрын
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)
@0xW0L0L07 жыл бұрын
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
@yassineghariani15057 жыл бұрын
This won't work if the number exceeds the integer type limit.
@0xW0L0L07 жыл бұрын
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
@spiderous6 жыл бұрын
Marcelo Ely Ok, but what about other languages? Your solution should be universal.
@raymondfellers38016 жыл бұрын
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.
@ShuskiCross6 жыл бұрын
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.
@donnygroulx45436 жыл бұрын
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 :)
@havalopez3 жыл бұрын
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.
@TheOriginalComments7 жыл бұрын
You bring great value.
@darshanpatil68923 жыл бұрын
```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!
@stockhutzo5 жыл бұрын
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; }
@julianelischer5 жыл бұрын
one word for you, pointers..
@stockhutzo5 жыл бұрын
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)
@yacinechettabravenclaw28324 жыл бұрын
I loved it, thanks. Ps: you could've used break in: Else: carry=0; break ;
@gunnu4u5 жыл бұрын
In JavaScript you can do: function addOne(arr) { var str = arr.join(''); str = (Number.parseInt(str) +1) + ""; arr = str.split(''); return arr; }
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]
@yeshwanthchowdary5 жыл бұрын
In scripting languages, array length is not fixed. Therefore, in JavaScript we can do parseInt(givenArray.join(''))+1
@AdamSafadi5 жыл бұрын
It doesn't return an array but only the total
@joshualim84715 жыл бұрын
@@AdamSafadi then make it array after you did this. Correct me if i am wrong. 🙂
@AdamSafadi5 жыл бұрын
@@joshualim8471that's right ((parseInt([9,9,9].join(''))+1).toString()).split("")
@ev.c62 жыл бұрын
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
@DemenciaSenil06 жыл бұрын
join -> convert to int -> add 1 -> split
@bikasgupta44545 жыл бұрын
Great course preview sir but i don't have money to buy that course but thanku
@RonitGhosh6 жыл бұрын
the easier way would have been to convert the array into a number, add 1 and then convert it back to an array
@Andr3ymzq6 жыл бұрын
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-Lin7 жыл бұрын
intern season got this guy so many subscribers
@Yotanido7 жыл бұрын
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)
@moritzschmidt67915 жыл бұрын
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); }
@jimnewton45346 жыл бұрын
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?
@ContortionistIX5 жыл бұрын
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
@panjc85435 жыл бұрын
i like your solution, its simply bcuz u only work with 2 variables
@adarshchaudhary53626 жыл бұрын
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