Master Data Structures & Algorithms For FREE at AlgoMap.io!
@millfreedom
4 ай бұрын
You need to add quick return for the case of difference between string lengths.
@e889.
4 ай бұрын
Keep them coming 👏🏼
@navneetchouhan7401
4 ай бұрын
I agree
@allamtajusarof5649
4 ай бұрын
this type of video is fun and entertaining while still being informative (A) I actually like point A, but you give both, A and B, and that is amazing. thanks
@GregHogg
4 ай бұрын
@@allamtajusarof5649 Haha glad to hear it! You're very welcome :)
@ibrahemfares1089
4 ай бұрын
return Counter(s) == Counter(t) 🗿🗿
@Broadsmile1987
4 ай бұрын
oneliners aren't ideal, because they make for worse GIT diffs, as well as error messages (granted, new Python error messages will report specifically the place on the line that causes a problem, but I think it's still easier to debug when the lines are separated), plus multiline code makes it easier to add something between operations e.g. logging messages. You may not see it on a video showing a result, but when e.g. discovering an API you may want to e.g. log what the resulting counters are, and it's harder to do when you have a oneliner. Also not really shown here, but giving temporary names makes for a good replacement of comments enhancing readability of your code. Cheers!
@Jiglias
4 ай бұрын
@@Broadsmile1987maybe in production, but one liners are cool
@Broadsmile1987
4 ай бұрын
@@Jiglias wdym "maybe in production", my arguments don't apply just to production. In fact some of my arguments were specific to development (debugging, git diff).
@TomzaBKewl
4 ай бұрын
@Jiglias where tf do you write the code before it gets to production 😂😂😂
@Jiglias
4 ай бұрын
@@Broadsmile1987 prolly should've been more clear. One liners are cool, but unreadable, but if you know no one else is going to read them then they are just cool.
@alxjones
4 ай бұрын
This is less rookie vs. senior and more unprepared rookie vs. prepared rookie.
@bacsibela8966
3 ай бұрын
why? what would be your solution?
@stopthecap2644
3 ай бұрын
@@bacsibela8966Kek, I’m wondering the same.
@bacsibela8966
3 ай бұрын
@@stopthecap2644 im genuinely interested. i have 15+ years in python and id probably do it the second way, lol. also worth noting how unlifelike is to spend any thought optimising this task in itself...
@dimanarinull9122
3 ай бұрын
@bacsibela8966 well... there are implementations that don't require two hash tables, and depending on string constraints some that fit on the stack in O(n) time while reducing the O(1) overhead of allocation and initialization to a cleaner solution. As O(1) overheads are rarely optimized in code by rookies and can often take more time than the average operation of the O(n) segment while still being invoked on every function call. As he said - this is prepared rookie, not an efficient and elegant solution. Additional points: why and when is string sorting a valid solution to this problem?(there ARE cases, not in python)
@jcd-k2s
3 ай бұрын
@@dimanarinull9122 I thought it worked because sorting the strings end in two identical strings if they are the same, no matter the coding you chose for your characters, and different ones if they are not. What is the problem exactly?
@Taurdil
4 ай бұрын
problems with strings such as this one that solved by hash maps could usually be optimised further by counting in array instead of hash map (lower constant in O(1)). Hint is "ascii only characters". This is how you get to top 5% in both speed and memory So iterate s, incrementing stats[s_char], then iterate t, decrementing. Return true of stats has all zeroes
@GregHogg
4 ай бұрын
Yes you're absolutely right I love the speed of these
@vibovitold
4 ай бұрын
you can optimise it for edge cases by iterating over both strings simultaneously, giving up when a failure is inevitable. for example, if you've counted 19 more letters "s" in one string than the other, and there are only 18 characters left, there's no point in iterating any farther, because there's no way for the other string to "catch up" anymore.
@keshamix_
3 ай бұрын
I'll be honest -- I didn't understand almost a single thing you said. Could you provide any clarifications or links/materials to what you just said?
@Taurdil
3 ай бұрын
@@keshamix_ in other words, when you use something like Map where characters can be very limited and continuous (ex. a-z or A-Z), you can use an array for it like array[ch-'a']. This removes hashing and collision resolution logic that would've happened if Map(Dictionary) is used. You use the value of your char minus starting value of your character range ('a' in the example) to offset indexes so that 'a' = 0th, 'b' = 1st, etc. You can use it even if you have some gaps in the range of valid values, but you would have to write "calculateIndex" method that does it correctly. In some cases, this logic could be more complex than just hashing.
@keshamix_
3 ай бұрын
@@Taurdil isn't it how the values are actually represented? Let's say, if we were to write like that using Rust, the strings are just bytes anyways, so what's the point of subtracting a constant value from them? Does it make sense for any size of solution or only for very large texts, so that you can store smaller values (up to size of the alphabet, instead of the size of the integer (32-64 bits)?
@riley25321
4 ай бұрын
the answer is somehow always hashmaps
@chickenbobbobba
4 ай бұрын
hashmaps are great
@riley25321
4 ай бұрын
@@chickenbobbobba oh yeah don't worry, i love hashmaps!! It's just amusing that they are almost always the answer to these kinds of problems
@chickenbobbobba
4 ай бұрын
@@riley25321 agreed, im a bit of a beginner to programming but ever since i stumbled across them, ive used them ever since lol
@bgdgdgdf4488
3 ай бұрын
@@riley25321either hashmaps or image processing algorithms
@ashwinsnmv
2 ай бұрын
Hash maps are solution to most leet code problems. But not very optimised for production grade setup
@Basta11
4 ай бұрын
In practical code, sorting an array can be faster and more memory efficient than creating objects and hashing if we don't expect huge n's. In many cases, we don't.
@italktocomputers1901
4 ай бұрын
these exercises are not about practicality, or maintainability. However in interviews being able to communicate that will give you bonus points.
@shrayesraman5192
4 ай бұрын
Its not sorting in place. So maybe slightly more efficient depending on hashing algo and space requirements
@AntonioZL
4 ай бұрын
I find it ironic that people spend so much time on leetcode solving problems that are only ever useful for coding interviews. Advent of Code is much more useful for working on your actual problem solving skills.
@drmonkeys852
4 ай бұрын
That is true after all big O always assumes n is huge
@b3arwithm3
4 ай бұрын
@@AntonioZLwe just play the game to get the job. We don't have to code like that at work.
@Leafycoke
4 ай бұрын
The point of leetcode is to try the brute force way first then learn the optimised method and apply that to new problems.
@DodoLP
4 ай бұрын
no
@dylanisaac1017
4 ай бұрын
?
@IRGhost0
3 ай бұрын
No, the point of interviews is to first give a mediocre, unoptimized solution, then whip out your good solution when they ask if you can do it more efficiently.
@Motionlesscapture
4 ай бұрын
Print (“hello world”) 👍
@GregHogg
4 ай бұрын
Great program
@TheNostalgiaDaily
4 ай бұрын
I would have fuckin used loops
@hollidaycursive
4 ай бұрын
I didn’t know there was a solution other than loops for anything tbh
@malusmundus-9605
4 ай бұрын
Get er done
@Farhan-h6i
4 ай бұрын
lol my fingers always go for forloop when idk what to do
@mpak96
3 ай бұрын
In reality the sort function or hash map use loops so...
@ladro_magro5737
4 ай бұрын
O(n) and extra space noob😂
@amichaeel
4 ай бұрын
First solution still uses extra space from creating the two new lists...
@fpskkkk
4 ай бұрын
The average is O(1), the max size of each Counter is 26 (from a to z)
@TheAcebyte
2 ай бұрын
Constant space too 😂🫵
@hlubradio2318
4 ай бұрын
Oh anagrams are words using the same letters?
@bart2019
3 ай бұрын
"Sort is n log n!" Dude, you're sorting about 10 items, so the O of the algorithm is irrelevant.
@GregHogg
3 ай бұрын
Where did you get 10 from?
@janekschleicher9661
2 ай бұрын
Maybe avg length of a word * 2 (as safety margin). I'd also choose the sorting way as preferred unless there are real reasons why speed would matter. It's just not obvious whether the Counter(s) == Counter(t) really works, just as it is not clear how the == is implemented (compares it object addresses, does the order in the counter matter, which time complexity does counting and comparing have) and also it's something quite rarely used and if you have a solution that's crystal clear and only uses constructs well known is better unless the performance really is critical about solutions with rare constructs. And Counter is very rare. Even as senior Dev, you only use it maybe once every 2 or 3 years, if ever. Usually you sort, use dictionary, use pandas value_counts or pyspark or SQL in situations with bigger data. Beside that, in practice you can't ignore utf and then you have to tackle that the there are symbols that represent multiple letters in one symbol. So, the more difficult part here would be to first canonical represent both strings so this would be handled and you also have to check first in which way the strings are encoded. (Yes, python strings are always unicode, but still an underlying encoding from cp1258, latin-1, utf-16 (and in case which one), uri-escape and so on, might still leak in some of your data whenever it's connected to some real, practical data system used over some years. And that's not trivial to detect, test and fix accordingly as the answer might need communication with subject matter experts about. So, wasting time and energy for a (in most cases) pseudo problem for runtime, might hide the real problems here. In practice, you will still have to run time complex diff similarity algorithms or fuzzy searches to find such problems. And yes, if you want to have good data quality, you also need to run them to some part on the real data at runtime, so you can e.g. alert and mark for manual inspection if words (or their sorted versions) with very high similarity occur, but anagram like differ. I mean, such an anagram check might be part of cross custumor system detection, or fraud detection, or database harmonization or spell checker or similar. So algorithmic complexity is only one of many considerations, and in practice, unless the system is slow from end user experience, a marginal problem compared to the real ones.
@astral6749
4 ай бұрын
I could easily solve this in C, but not in Python. In C, I'd just make an int array of size 26, iterate through the string while doing +/- 1 on the corresponding array elements, and check if the array has a non-zero. Easiest O(n) ever.
@vibovitold
4 ай бұрын
26 if only the Latin alphabet is allowed (and no digits, and casing doesn't matter etc.) Never assume such things if they're not stated explicitly in the task description
@astral6749
4 ай бұрын
@@vibovitold Well... yes. The constraint for this Leetcode problem specifies that strings s and t consist of lowercase Enhlish letters. That's English letters from a to z so 26 works for this specific problem.
@vibovitold
4 ай бұрын
@@astral6749 the description on the screen, in the video, doesn't say so
@mujtabarehman5255
4 ай бұрын
If you can solve a problem in C, you can figure out how to do it in Python without too much trouble. However the inverse is not always true.
@astral6749
4 ай бұрын
@@mujtabarehman5255 That's true. Just need to learn how Python works.
@nk361
2 ай бұрын
I'd rather go forward through one and backward through another instead of using the hashmap, more clear, more fun, less space, and makes more sense to anyone who sees it
@MrBranh0913
3 ай бұрын
Senior devs are actually solving real problems, and are usually annoyed when they have to solve problems like this
@GregHogg
3 ай бұрын
This is very true haha
@lOmaine777
4 ай бұрын
This would require a space of o(m+n) which can be reduced to o(n) by only storing count of s in hashmap and decrementing count while traversing t. If -1 os even reached, return false.
@fspieler
4 ай бұрын
If m and n aren't the same then they're not anagrams so O(m+n) is equivalent to O(n) if you check length first
@ZeruelB
4 ай бұрын
from experience, this comes up like never and most stuff thats breaking or causing issues is the architecture and/or used frameworks and/or libraries
@ShinAkuma
2 ай бұрын
Still a bad solution. take an integer array of size 26. increment (s1.charAt(i) - 'a') in a loop. Then decrement (s2.charAt(i) - 'a') in a loop. Check if the array has any non-zero value. The complexity is O(s1Lenth + s2Length + 26) = O(n)
@HhddGufif
Күн бұрын
I wonder if you used bit packing or flags on the most common letters to build a checksum value. Then compare on both to break early for 99.99% of cases. The. For the remaining do any slower verification, doesnt matter for performance
@hmkl6813
4 ай бұрын
Lol, coding is a really cool thing for me. I love maths, but not only to have to find a solution, but also optimize it is really challenging
Btw, I offer personalized 1 on 1 tutoring services for data structures and algorithms / career mentorship. Please email greg.hogg1@outlook.com for inquiry :)
@numbdigger8558
2 ай бұрын
Lmao, if you wanted to over-optimize your code like that: 1. You wouldn't use hash tables. A single array indexed from 0 to 25 (or from 0 to 255 if we allow all ASCII characters) is faster. 2. You wouldn't use Python, lol.
@exiled1gaming
2 ай бұрын
99.999999% of the time, either will work fine
@thegoodhen
2 ай бұрын
Me: Eh, convert both to lists, go over the first list and if you don't find the letter from the first list in the second, they aren't anagrams; if you find it, remove it. It's O(n^2), but hey, that's still gonna be fast for most reasonable inputs... if not, you can always use 2 arrays for the numbers of occurances of each letter and compare them, I guess...
@ungrim97
3 ай бұрын
The expert dev is the one that realises that your prod code probably wouldn't notice the difference between the two solutions but broke because someone asked if 🤢💛🍇🍊🍌🍍🍎 is an anagram of 🤢🍎💛🍇🍊🍌🍍
@alex85hst
2 ай бұрын
Uh, check equal length first and just start an index i at zero and compare chars at i and s[i] and t[len(t)-i-1]. O(n) without hashmap allocation.
@thibauldnuyten2891
2 ай бұрын
"Oh just use a hashmap"... This is not a solution. This is like taking someone else's solution and copy-pasting the answer. To solve these you need to write something yourself.
@unhhgcrxexhjvuvujchcrzwzwz7956
4 ай бұрын
I had to do this in mips once and it was so hard lol
@absolutetrash9963
2 ай бұрын
All fun and games seeing different solutions to problems, however, serious question from a beginner: what would be a real life usecase for this thing?😅
@yagan_dawn2008
5 күн бұрын
Can’t we make a hashmap of the first word, then take each letter of the other word and check if it is in the hashmap?
@NikhilChoudhary-hi6fo
17 күн бұрын
Juat take 2 arrays of size 26 and atore the count of the characters. Its 0(1) space and 0(n) time
@icarus5721
3 ай бұрын
Set equality
@renierbarnard2999
3 ай бұрын
Or you do: If (len(s) != len(t)) return false For (i in range(0, len(s)) If (s[i] != t[-i-1]) return false Return true
@widosvbraun
3 ай бұрын
Thought the same but it's anagrams and not palindromes. Noticed quite late as well ^^
@renierbarnard2999
3 ай бұрын
@@widosvbraun shit
@sandyg857
Ай бұрын
There's a solution with constant space. Using an array of length 26 and index using ascii basis ascii of 'a'
@tylocrocket6111
4 ай бұрын
Oh man, I'm just about 2 weeks into learning coding (Python) as a COMPLETE noob. And these shorts got me stressing (from not knowing anything), but excited to eventually learn this!
@GregHogg
4 ай бұрын
You've got this just be patient 😊😊
@tylocrocket6111
4 ай бұрын
@@GregHogg Thanks a lot man 😊
@mahmad8528
4 ай бұрын
Same, when I saw python programs my mind was nuked.
@supernat1978
3 ай бұрын
Don't worry, I've been writing software for 22 years. You will always feel like you don't know anything. I juggle 5 different languages at the moment, and context switching between them has scrambled my brain. I try to do array pushes in python and array appends in javascript, and luckily since they are untyped, it will happily compile. Just remember, Google will be your friend the rest of your career. And as you get older, you'll need it more and more.
@mahmad8528
3 ай бұрын
@@supernat1978 If I were to become a programmer, whats a good age to start learning code. I already know the basics of python up to classes and objects. And also when did you start.
@mohammedsifankp9785
Ай бұрын
class Solution(object): def isAnagram(self, s, t): if len(s) != len(t): return False dicts = {} for i in s: dicts[i]= dicts.get(i,0)+1 for i in t: if i not in dicts: return False dicts[i] -=1 if dicts[i]==0: del dicts[i] return len(dicts)==0
@bobsemple9341
4 ай бұрын
This is slightly bs and playing off new devs insecurities. Most senior devs won't care. A few Ms here and there in what's most likely a medium sized application doesn't matter. Write the code well. Name your variables well. Which this guy didn't. And you'll be fine. If it needs improvement later. The implementation can be improved in that function. Don't solve problems you don't have
@GregHogg
4 ай бұрын
It's about the efficiency of the code for a coding interview. You're totally right from a typical software engineering pov 😊
@bobsemple9341
4 ай бұрын
@@GregHogg should interviews not mirror software development though? And if not. Is that really a company you want to work for?
@ghdshds1899
3 ай бұрын
most likely the senior developer would implement an even worse solution because we do not think about leetcode or dsa questions at all in day to day life
@ttt69420
2 ай бұрын
neither of these explicitly check if its an anagram. edit: nvm im thinking of palindrome.
@esceip4847
3 ай бұрын
Bogogram: shuffle one of the strings until it matches the other one Bonus points if you dont store previous shuffles and just set an absurdly big amount of time and hope this will check all possible shuffles
@HoverCatzMeow
2 ай бұрын
Leetcodes timer system is broken. Run the same code several times and you get numbers all over the place
@eneadon6592
3 ай бұрын
see, the funny part here is worrying about small inefficiencies while using Python.
@maxjiang1324
3 ай бұрын
Love how simple and stupid Python with all these libraries can be.
@KX36
4 ай бұрын
easy optimiation: first compare the lengths of the 2 strings and return false early if they are different lengths.
@GregHogg
4 ай бұрын
Yes you're absolutely right!
@namegoeshere8458
2 ай бұрын
So what is the best solution since this only beats 65% of users
@StandOnDev
2 ай бұрын
Use one frequency table thats it and check it no need to sort
@rachitchauhan8164
Күн бұрын
Still beats on 54% what a shame, waste
@malusmundus-9605
4 ай бұрын
I mean, they both have the same result. If performance is an issue than why use python? The program just determines if something is an anagram anyway... it's trivial and useless. Performance is a non-issue here. Not hating on python, it is a useful language for many reasons.
@hiroyoshiarai8776
4 ай бұрын
This is an exercise to optimize your codes for time complexity.
@ajaypatro1554
4 ай бұрын
def are_anagrams(s1, s2): freq1 = {} freq2 = {} for i in s1: if i not in freq1: freq1[i] = 1 else: freq1[i] += 1 for i in s2: if i not in freq2: freq2[i] = 1 else: freq2[i] += 1 return freq1,freq2 a = are_anagrams('ajay', 'jaay') a[0]==a[1] what about this raw dogged dict opertions
@GregHogg
4 ай бұрын
😂😂 terminology is very interesting
@arijitdas7526
Ай бұрын
Having the same isuue with i9 raptor lake.
@youtubeaccount1746
4 ай бұрын
Your senior eng solution is O(t) + O(s). I think you can optimise this further by return false early during the counting of s, if the current char is greater than t's count for the same char, or if the char doesn't appear in t at all. Now, it's just O(2t) time = O(t).
@GregHogg
4 ай бұрын
Yes you're right we should definitely add in that line :)
@ROCKSTARGOD98
4 ай бұрын
If len(t) != len(s) then it's not an anagram, so O(t) + O(s) = O(2t), this would be an an optimisation, but not an improvement in complexity
@youtubeaccount1746
2 ай бұрын
@@ROCKSTARGOD98 The senior eng solution in the video counts the whole of s and counts the whole of t, so it's O(t) + O(s) as it has to loop through the whole of both. Whereas what I suggest is O(t) as it doesn't loop through the whole of s, only the first t characters of s.
@immortalroasterben7146
2 ай бұрын
Bruuh i literally did this using stack in C 💀
@AbhishekTiwari-xt1kt
3 ай бұрын
Space complexity can be reduced to half
@alexthezephyr
3 ай бұрын
You don't even need to create a hash map wtf
@SbuZungu
4 ай бұрын
What's up with every code a hashmap
@Lingura123
3 ай бұрын
All the cool kids do it.
@85dot6
Ай бұрын
does this guy only know hashmaps
@vickyvk5889
10 күн бұрын
return set(s) == set(t) ....?
@crawlingrocket116
4 ай бұрын
In the real world I would use an array for storing the counts of each letter. But just for fun I implemented a solution that packs the counters into a 128-bit integer. Works splendidly as long as no character appears more than 15 times in a word. Anyway, I'm not sure it gave me any extra performance.
@GregHogg
4 ай бұрын
Yeah that's a great idea too
@artfol2
4 ай бұрын
If care that much then don't use Python
@GregHogg
4 ай бұрын
😂
@tollmlg7852
4 ай бұрын
python is so bad that hashmaps are more efficient than making your own "array" solution. You don't even have anything close to a real array out of the box either, you need numpy for that. And that doesn't even work that well either because everyone knows that you don't ever loop in python if you want the program to finish in this lifetime.
@Dennis450D
3 ай бұрын
Nah. Create an actual hashmap from the first value tracking the frequency of every character. Then deduct the frequencies on every character of the second value, removing altogether when 0. If you don't find the key at any point in the second value return false. Then return a check on whether the map is empty
@gabrielbarrantes6946
4 ай бұрын
That's slow AF... Just loop through the strings O(N)...
@GregHogg
4 ай бұрын
With what algorithm lol
@lakshyabhardwaj2146
2 ай бұрын
In java, this is minimum 20 lines
@cdjamse3944
4 ай бұрын
You get 20 minutes to do this in A level cs and he did it in 30secs
@GregHogg
4 ай бұрын
Lol I've also solved this before
@Max-E-Mum
21 күн бұрын
you can use xor as well
@lonli2020
3 ай бұрын
camel case in python ☠️
@tusharrai9762
7 күн бұрын
Love your content
@rishujeetrai5780
2 ай бұрын
O(n) with space complexity of O(n) as well Or O(nlogn) with space complexity of O(n) Make sure to tell both approaches the interviewer PS- Since python doesn't let you sort string in-place both approaches are O(n) space for python developers
@trillex1861
Ай бұрын
A hashmap? Use an array
@hassan7569
3 ай бұрын
the lip syncing lmao
@sharp764
3 ай бұрын
Doing leet code in python is like using cheat codes lol
@GregHogg
3 ай бұрын
Feels that way sometimes
@shrijitsrivastav5392
2 ай бұрын
return set(s) == set(t)
@TheRealDeevz1
2 ай бұрын
This can be improved in terms of space complexity. If you use the bitwise XOR operator, it is still O(n), but the space complexity is O(1).
@crazyhussar
3 ай бұрын
what is this website
@rachellejanssen2655
3 ай бұрын
We can all debate what the best solution is, but I think we can all agree that nobody except the senior developer who rewrote it cares. As long as you're on track with the burndown and write on or above minimum quality code... :(
@ilikegeorgiabutiveonlybeen6705
3 ай бұрын
its always hash map
@coolcodingcat
2 ай бұрын
I was going to make my own counter maps from scratch with char keys and number values. I imagine Counter is just the same solution with that boilerplate code already done inside Counter.
@jvcss
4 ай бұрын
I would loop in one of them and check if each char is present in the other string. Or I would use ord() and check of they are equal. no need import needed
@nigh_anxiety
4 ай бұрын
each check for "is char in second_string" is an O(len(second_string)) operation, and you're basiclaly at O(N^2) time complexity. Using ord() to add up character values also doesn't work, because sum(ord(ch) for ch in "abc") == sum(ord(ch) for ch in "bbb")
@thekwoka4707
4 ай бұрын
Neither of these would actually work.
@rahuldwivedi4758
3 ай бұрын
Plot Twist: The space was needed to be managed for the program so the Jr. developer didn’t use hashmap. Now it’s broken in production and everyone’s looking for the sr. Developer who modified it.
@aravindk8181
3 ай бұрын
One hashmap is enough.. we can subtract from the hashmap of first string.. and if a char is not found we could return right there without iterating all of string 2 .. at the end if map value is all 0 .. they are anagrams
@n1ckstars
3 ай бұрын
could you not just do which reverses the s variable and compares it to t
@kevindustries9130
3 ай бұрын
Practically, lots of interviewers would immediately ask you to implement a more generalized solution that doesn't use Pythonic tools like Counter().
@Terrados1337
3 ай бұрын
Is optimizing code just reducing CPU operations while telling the customer to buy more RAM?
@NaHBrO733
3 ай бұрын
I would loop through s, adding a counter for every character using dict. Then loop through t and decrease the counter (and return false when not in dictionary) Then check the values to see if it is all zeros. It's O(n) and it's good enough
@aravinth_
4 ай бұрын
Which IDE he use?? Someone tell me
@GregHogg
4 ай бұрын
Leetcode
@imakhlaqXD
3 ай бұрын
Senior Dev More like : Calculate the ASCII values of both the string if they are equal its anagram. And in this solution i dont have to use extra space.
@val8715
3 ай бұрын
Nope, that just checks if the same letters exist in both strings not to mention it doesn't even work for that because b+d would be equal to a+e
@jcd-k2s
3 ай бұрын
The insane efficiency of sorting algorithms. I will always be a rookie, but I would never have thought about sorting them. I would just have read the letters in reversed order. (and checked the size first)
@stefanopalmieri9201
4 ай бұрын
Don't create the second counter, as it double memory allocation. Count up and then count down. Use the .any() method to check for all zeroes.
@tryoasnafi4340
3 ай бұрын
1. Check the length 2. Compare with two pointer, move forward-backward
@gast128
4 ай бұрын
Perhaps use only lookup and remove in one string s faster. It's debatable then if presorting, hashing or just a lineair search is the fastest since e.g. unordered_maps in C++ are not cheap to create. For short strings the lineair search (in contiguous memory) probably beats them.
@rafazieba9982
2 ай бұрын
What if the letters in a word are not unique? What kind of HashMap do you have in Python?
@ridabrahim7604
4 ай бұрын
As you learn how to code and you start implementing some absractions it's easy to understand how your advice is valid, fix the algorithms problem first it's an independent thing that is a piece of the big system, solving a problem in leetcode means solving your knowledge of algorithms first and then jumping to reuse that piece of algorithm to deal with the bigger picture a system or a program, thanks a lot
@tomaszenko13
3 ай бұрын
In real world we solve business problems and most important aspect of the code is readability.
@jffrysith4365
4 ай бұрын
tbf for this question is clearly a hashmap problem. Probably not a good idea - in an interview, or even to practice - to solve the questions with a tool that has the solution as a single operation...
@benjaminluzier3734
10 күн бұрын
Love this channel
@GregHogg
10 күн бұрын
Thank you!
@code2compass
4 ай бұрын
Hahaha nice story telling bro
@GregHogg
4 ай бұрын
Hehe thank you 😊
@juanmacass
4 ай бұрын
And what s de cost of Counter? Best case O(n), if the hash search is very good with no collisions. So O(n log n) vs O(n). If u r working with short strings, there is no difference in practice. An Engineer knows if it worth spending more time optimizing a solution or if not. If you are working with strings with length less than, let's say, 100 chars, unless you have a atrong reason to make the function run 1 nanosec faster, you shouldn't waste time trying to optimize it.
@Schnorzel1337
3 ай бұрын
Collisions dont matter. If your string is abaaaa the map would be: (a,1) (a,1),(b,1) (a,2),(b,1) (a,3),(b,1) (a,4),(b,1) (a,5),(b,1) There is no worst case. Technicly I suppose it is even faster if everything is a collision due to paging and caching.
@donsanders9889
4 ай бұрын
Counter average case insertion is O(1) per element but worst case is O(n). Counter solution worst case is slower than sorting.
@nonconsensualopinion
4 ай бұрын
Sorting is O(n*log(n)), which is worse than O(n), except when n is small. Sooo...how is counter slower?
@donsanders9889
4 ай бұрын
O(n) per element, so O(n^2) for n elements. This is only in the worst case. I think it would require all elements being distinct and having hash collisions.
@thekwoka4707
4 ай бұрын
Sorting is O(n log n) and counter is O(n). Counter is still worst case better than sorting worst case.
@donsanders9889
4 ай бұрын
@@thekwoka4707 Counter is O(n) average case, but O(n^2) in worst case, where all characters in the string have hash collisions.
@Schnorzel1337
3 ай бұрын
@@donsanders9889 You are not understanding what Counter does. Assume the hash function is the identity. Then Counter is an array and all you do is: arr[char]++; Now explain where the O(n) insertion comes from.
@yairlevi8469
4 ай бұрын
senior doing leetcode, lol
@KX36
4 ай бұрын
must have a job interview coming up
@kolyashinkarev7366
2 ай бұрын
I wish junior developer interviews had questions like these
Пікірлер: 319