Тёмный
No video :(

Largest Number - Leetcode 179 - Python 

NeetCode
Подписаться 787 тыс.
Просмотров 54 тыс.
50% 1

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: / discord
🐦 Twitter: / neetcode1
🐮 Support the channel: / neetcode
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
💡 BINARY SEARCH PLAYLIST: • Binary Search
📚 STACK PLAYLIST: • Stack Problems
Problem Link: leetcode.com/p...
0:00 - Read the problem
1:25 - Drawing Explanation
5:13 - Coding Explanation
leetcode 179
This question was identified as an interview question from here: github.com/xiz...
#amazon #interview #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Опубликовано:

 

14 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 70   
@nikkil7428
@nikkil7428 Год назад
You are the best one yet. Your videos had been helping me so much, from struggling doing medium, to now conquering medium leetcode. Your positive energy also giving me such a good vibe to work on supposed to be boring and painful leetcode questions. ❤❤❤ Thank you.
@rakoonberry7879
@rakoonberry7879 2 года назад
I'm not sure if your str(int(..)) solution at the end is the best way to go about it. The problem says that the number may be large (i.e. overflow) so we are asked to return a string. A loop would probably be a better albeit less elegant answer.
@jessesinger4790
@jessesinger4790 4 месяца назад
Can just check first value of string too, concatenatedString[0] == '0' ? "0" : concatenatedString
@rhosymedra6628
@rhosymedra6628 2 года назад
great explanation! tried this on my own, got stuck, and came here to listen to your explanation.
@aswinbarath
@aswinbarath 4 месяца назад
I struggled a more than 1 hour on this problem by doing it myself without the knowledge of Custom comparator concept. Thank you so much for this solution bro!
@stephenbouldin8163
@stephenbouldin8163 2 года назад
As someone new to python, and coding in general, I learn something new in each of these videos. However, it would be more helpful if you explained the functions within the class a little more.
@OneMoreLight1
@OneMoreLight1 2 года назад
nums = list(map(str,nums)) this will convert every int list element into str and store in nums . Python ❤️💕
@shrimpo6416
@shrimpo6416 2 года назад
Thank you!!!
@OneMoreLight1
@OneMoreLight1 2 года назад
@@shrimpo6416 WC Bro
@leeroymlg4692
@leeroymlg4692 Год назад
nums = [str(num) for num in nums]
@rohanchess8332
@rohanchess8332 11 месяцев назад
@@leeroymlg4692 This is what I did too!
@fer-ic1wh
@fer-ic1wh 2 года назад
for those who don't understand the cmp function. paste source code here def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" class K(object): __slots__ = ['obj'] def __init__(self, obj): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) = 0 __hash__ = None return K
@AlexSav
@AlexSav 2 года назад
0:25 It may be very large, so return string instead of an integer 10:35 - Just convert to an integer and then back to string Genius!
@jfcherng
@jfcherng 2 года назад
lol... worked since Python has auto big number handling. return ''.join(nums).lstrip('0') or '0'
@redfinance3403
@redfinance3403 4 месяца назад
My solution was pretty ugly and consisted of making the number into separate digits within a map of maps of maps ... and then sorting each map in descending order based on the key. Then recursively iterating over the digits and eventually adding them in order to the answer. This comparator idea is very smart and its amazing how the idea didn't come to me earlier given the fact that my code is basically selecting the best possible order to add them in. Once again, amazing video!
@longschlongify
@longschlongify 2 года назад
Great video, but I have a question. Why do we return 1 and -1 in the compare function instead of the actual n1 or n2 itself?
@FCBarcelonaXMI
@FCBarcelonaXMI 2 года назад
The way cmp_to_key function works is that you pass it a method (compare) that will either return -1, 1, or 0 in order to sort the items in the list. You don't actually need to return the values themselves because it just has to compare them to know which item is less or greater, then it will automatically sort the items.
@longschlongify
@longschlongify 2 года назад
@@FCBarcelonaXMI Thanks! That makes sense!
@navamshuram
@navamshuram 2 года назад
@@FCBarcelonaXMI My doubt is why we should return -1 for n1 going first ??
@FCBarcelonaXMI
@FCBarcelonaXMI 2 года назад
@@navamshuram I don't know if there is a particular reason why, that is just the way cmp_to_key function is designed to work in Python.
@cocoatut49
@cocoatut49 2 года назад
@@navamshuram I think this function sorted the return value. If the return value is -1 then it goes first.
@jimmycheong7970
@jimmycheong7970 2 года назад
I ended up writing a recursive comparator function which took me ages to figure out properly! Only I had submitted a successful solution did I find out you can just add the nums strings as strings in different orders. 🤦🏻‍♂️. Thanks for the video as always!
@el_chivo99
@el_chivo99 2 года назад
great solution. never knew about cmp_to_key until now!
@FACS01
@FACS01 2 года назад
Careful that converting str to int for handling the 000 case could produce overflow in large numbers
@NeetCode
@NeetCode 2 года назад
That's definitely true, python makes it work but in other languages it probably won't work.
@nandhakiran6523
@nandhakiran6523 2 года назад
We can avoid that, just check if the sorted arrays first element is "0". if so, that means everything after it will also be "0" so we can just return "0" right there :) And if that is not good enough, we can sum the initial array, if it is 0, return "0". But that decreases the efficiency of the code.
@HelloJaewon
@HelloJaewon 2 года назад
@@nandhakiran6523 Great! It's clear and does not dependent on programming language.
@sharksinvestment9864
@sharksinvestment9864 Год назад
Nums=list(map(str,nums))
@pammugaadu
@pammugaadu 2 года назад
Thank you very much for your valuable time. I really appreciate. If anyone is looking for Java code: public static String getLargestNumber(int[] input) { String output[] = Arrays.stream(input).mapToObj(String::valueOf).toArray(String[]::new); Arrays.sort(output, (n1, n2) -> { return (n2 + n1).compareTo(n1 + n2); }); String result = Arrays.stream(output).collect(Collectors.joining()); if (result.matches("^[0]*$")) { return "0"; } return result; }
@oneplusgeek7510
@oneplusgeek7510 2 года назад
Thanks!!
@monicawang8447
@monicawang8447 Год назад
Hey can anyone explain why we return -1 when n1 + n2 > n2 + n1? I'm confused about how returning -1 or 1 works here..Thanks!
@iaingavinsoutherland4369
@iaingavinsoutherland4369 Год назад
Hey, my guess is as good as any but I was playing around with it. We're trying to compare elements, e.g. if we have a='30' and b='3' (in python notation), we are trying to figure out if a+b ('303') is larger than b+a ('330'). The cmp_to_key function is part of the functools module, and tells the sorting to use our comparison method. So if we want to decide whether to put '30' or '3' first, we look at whether a+b or b+a is bigger. In order to tell the key which is better, in almost a boolean sense, we say positive means change/don't change order, and negative means don't change/change order. So if we get in a='30' and b='3', (note that in the key function, the first value is later, so we would have a list that had [......, 3, 30, .......] in there, if a+b > b+a (303 > 330, not true in this case), we would pass a -1 (red flag), and the key function would switch order to have [...., 30, 3, .....]. In real life, that case wouldn't be true, and the key function would receive a 1 (green flag) so that it wouldn't have to switch the two. Bit long, but it's an odd question. Can't imagine answering this in an interview. Also note that you could return any positive/negative (e.g. 420/-69), but you can't return a 0 or it gets screwy. The delineator is positive vs negative as switch position after comparison vs don't switch position after comparison.
@SkyeTian
@SkyeTian Год назад
1. This key is eventually helping sorted() to arrange elements in ascending order; 2. It returns a negative value indicating the first argument is lesser than the second argument or a positive value indicating the first argument is greater than the second argument. So if n1 + n2 > n2 + n1 we want to put n1 first so we must tell it that n1 is the smaller one thus return -1
@gskpsrikar1858
@gskpsrikar1858 2 года назад
Max length of the array is 100. So write simple sort algo in O(n^2) using the str comparator logic. Simple !
@HolyCowSoft
@HolyCowSoft 2 года назад
oh great and clear tip! thx
@miguelangelrodriguez8999
@miguelangelrodriguez8999 2 месяца назад
Thank you
@hueydo3522
@hueydo3522 5 месяцев назад
why if n1 is the bigger significant digit, we would want to return -1?
@rohanchess8332
@rohanchess8332 11 месяцев назад
Wait, how can you compare strings like integers, it compares the ascii value right, so shouldn't we use int(n1+n2) > int(n2+n1) ?
@jessesinger4790
@jessesinger4790 4 месяца назад
9 + 34 == 34 + 9
@user-hf7ef6nm4s
@user-hf7ef6nm4s 2 месяца назад
nlogn or knlogn where k is the avg. length of the strings were comparing?
@Cloud-577
@Cloud-577 2 года назад
Do we have to write out own sorting function in an interview?
@santoshrathod9868
@santoshrathod9868 2 года назад
You are a legend.
@nikhil199029
@nikhil199029 2 года назад
If we compare 9 and 930 then 930 has a higher value so this code should return 9309 instead of 9930? Not sure what am I missing.
@dakshbhayana237
@dakshbhayana237 2 года назад
it doesn't compare numbers individually , it compares after concatenating them.
@niharikkatyagi4089
@niharikkatyagi4089 Год назад
I'm not sure why, but this is returning a NULL value in each case when I try to run it. Is there any solution to this??
@neilgaliaskarov5341
@neilgaliaskarov5341 2 года назад
Can you please explain us Accounts merge problem from leer code? I just don’t understand other explainers…
@Cloud-577
@Cloud-577 2 года назад
I had the same idea but struggled to code it up :( how do I improve?
@shubhamsingla8182
@shubhamsingla8182 2 года назад
Please do 708. Insert into a Sorted Circular Linked List
@weaponkid1121
@weaponkid1121 2 года назад
What drawing program do you use??
@aprily5016
@aprily5016 Год назад
The sound feels like ASMR, which makes me personally feel disturbing. Content is clear
@its_me_tabs
@its_me_tabs 9 месяцев назад
Whats the time complexity?
@symbol767
@symbol767 2 года назад
Wow this is a genius solution wtf
@mickeymacke1780
@mickeymacke1780 2 года назад
Can you do 1721. Swapping Nodes in a Linked List?
@Dezdichado1000
@Dezdichado1000 2 года назад
can this not be done by a recursion?
@tanaypatel8412
@tanaypatel8412 Год назад
did anyone else tried extracting just the first character and arranging as such and got stuck.
@jugsma6676
@jugsma6676 2 года назад
I always solve my way before watching the solution, and this is my solution, def max_number(nums): res_lst = permute(nums) max_str_numb = -sys.maxsize for i in range(len(res_lst)): appended_str = ''.join([str(r) for r in res_lst[i]]) max_str_numb = max_str_numb if max_str_numb > int(appended_str) else int(appended_str) return str(max_str_numb) def permute(nums): if len(nums) == 1: return [nums] res = [] for i in range(len(nums)): head = nums[i] remainder = nums[:i] + nums[i+1:] for p in permute(remainder): buffer = [head] + p res.append(buffer) return res
@amarnathmishra8697
@amarnathmishra8697 Год назад
Damn You are good
@numberonep5404
@numberonep5404 2 года назад
I love it
@lakshyasaharan5348
@lakshyasaharan5348 2 года назад
First
@brogrammer8783
@brogrammer8783 2 года назад
Fourth
@saurabhverma7366
@saurabhverma7366 2 года назад
555
@awukugodfred6610
@awukugodfred6610 2 года назад
Third
@shrio272
@shrio272 2 года назад
Second
@navamshuram
@navamshuram 2 года назад
def comp(a,b): if (a+b)>(b+a): return -1 else: return 1 # arr.sort(key = functools.cmp_to_key(comp)) ans="".join(arr) return ans
@linggesarulsamy
@linggesarulsamy 2 года назад
I wrote the function in JavaScript: 1) Arr_To_Single_String = Array.join(""); Convert the Interger Array to a Single String: [10, 2] => "102" 2) Arr = Arr_To_Single_String.split(""); Split the String to each character individually in Array; "102" => ["1", "0", "2"] 3) Sorted = Arr.sort().reverse(); Sort the Array in descending order ["1", "0", "2"] => ["2", "0", "1"] => "210" function sortString(Array) { let Arr_To_Single_String = Array.join(""); let Arr = Arr_To_Single_String.split(""); let Sorted = Arr.sort().reverse(); return Sorted.join(""); } // Question 1 let Q1 = [10, 2]; console.log(`sortString(${Q1}) = ${sortString(Q1)}`); // Output: "210" // Question 2 let Q2 = [3, 30, 34, 5, 9]; console.log(`sortString(${Q2}) = ${sortString(Q2)}`); // Output: "9543330" // Question let Q3 = [10, 2, 5000, 321]; console.log(`sortString(${Q3}) = ${sortString(Q3)}`); // Output: "5322110000"
@jimmycheong7970
@jimmycheong7970 2 года назад
Actually you are supposed to preserve the order of the numbers so technically the answer you have for question 2 is incorrect 😕
@guruprasadv7972
@guruprasadv7972 2 года назад
Sixth
Далее
Remove K Digits - Leetcode 402 - Python
14:36
Просмотров 59 тыс.
Leetcode 149 - Maximum Points on a Line - Python
8:14
Big-O Notation - For Coding Interviews
20:38
Просмотров 446 тыс.
Largest number formed from an array
8:33
Просмотров 118 тыс.
Continuous Subarray Sum - Leetcode 523 - Python
14:56
Can You Forge Tungsten?
16:14
Просмотров 824 тыс.
Can you solve these number puzzles?
8:03
Просмотров 14 тыс.
Candy - Leetcode 135 - Python
13:45
Просмотров 27 тыс.
5 Useful F-String Tricks In Python
10:02
Просмотров 293 тыс.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36