Reorganize String
Vložit
- čas přidán 5. 07. 2024
- For business inquiries email partnerships@k2.codes SOCIAL
----------------------------------------------------------------------------------------------------------------
Instagram: / kevinnaughtonjr
Twitter: / kevinnaughtonjr
Patreon: / kevinnaughtonjr
GitHub: github.com/kdn251
MUSIC
----------------------------------------------------------------------------------------------------------------
look alive, please by erickD
/ look-alive-please - Věda a technologie
instagram: instagram.com/kevinnaughtonjr/
twitter: twitter.com/kevinnaughtonjr
kevin can you please do a video about 146. LRU Cache.thanks and have a good week end
Dude, you're awesome! Very genuine presentation. You don't try to be funny or hip, and you're not condescending at all. Thank you for these videos!
thanks really appreciate that and yep, just wanna be helpful!
laughed so hard at the last segment, lol!
haha thanks Abhishek
@@KevinNaughtonJr Should have tried running before hitting submit....😂👍🏻
Probably one of the best questions on LeetCode and impeccable explanation by Kevin.
The sound effects after every typo is hilarious
Amazing!! Lots of twists and turns! Utilization of Heaps blew my mind....fantabulous
That last segment really left me with a huge smile. Thank you for your videos. After watching them so many, I have started to approach these questions with much more confidence. For this question, I also had thought of using the same Data Structures but wasn't sure about how to update back and use the max and second max character.
anytime Shubham thank YOU for supporting my channel it means a lot to me!
What a great explanation to this problem, understood completely. I was finding a perfect explanation for it from last 2 days and then I landed here. I code in c++ and know nothing about java but you made every line so simple that I understood it completely. Keep uploading more such problems. Thank u...
Thanks a ton! Well explained. I landed here thankfully, after watching few other videos. The last segment of the video put a smile on my face :) Thanks again!
This probably is the best upload to me among all of your uploads, only because of the last segment. haha
Great job! Kevin, thank you soooo much for your wonderful videos!
you're AWESOME! I have been watching your videos for sometime now. They're so helpful! Thank you so much for taking a time to make these videos.
Anytime!
keep it up with the regular uploads, Kevin. Your videos make me happy.
Thanks Arpit really appreciate that :)
Even after practicing so much... i can't think of this amazing solution to this problem.. HatsOff :D
that's ok just keep practicing :)
Amazing explanation and hilarious music at the end, loved it!!
kevin you explain stuffs in such an awesome way dude, plz keep making videos like this, thank you!!!!!
Prakash Jha anytime and will do!
Seriously you gives every qsn a perfect explanation
Learnt and laughed at a lot at the same time. Thanks Kevin :)
Amazing explanation! Really enjoyed it 🙂
Thank you sir. You r doing a great job.
Realest in the game. Hey, can you just post a playlist of all the songs in your transitions? Always bangers.
Very Nice solution, I hope I remember in interview round
Awesome Explanation ! ,Thanks
Well Explained Solution, Thanks!!
dude love your explanations though I wish you would visualize and draw out your solutions for us more visually inclined learners.. keep on rocking it ~
I laughed a lot at the end with those sound effects lol
Nicely explained!
Great videos man!! Helping me out so much
Thanks dude and super happy to hear that!
Nice Explanation dude !
Clean && simple
Thanks for the videos! Keep up the work! ✌️
anytime and will do!
Hi Kevin, Can you tell me what software you use to edit the videos with the music in the beginning and the end. Is it some mobile app or some Adobe software ?
Very solid! Good one. Thanks
thanks!
I would just make a frequency vector, so that pos 1(or 0 if we're trying to be super strict about it) stands for how many times a appears, pos 2 (1) stands for how kany times b appear, and so on. Therefore we walk throught it from both ends to the middle. If, let's say, we went from 1-end with x and from end-1 with y and we paired 2 of the indices each step and added them to a new string, if we have x=y and vector[x] is not equal to 0, return null. Else, return the formed string.
Thanks for the explanation....
BEST EXPLANATION ON THE INTERNET!
Very very impressive. I cannot do this in interview time. Not sure how to improve my solving capability.Any pointer I can use to improve this?
Enjoyed the problem! I was wondering why not use heap.poll() instead of remove() ?
I love how there's hip hop at the start of all your videos
the music is key
@@KevinNaughtonJr which song is that ?
its playing in my mind since long and cant quite figure it out
Thanks! Nice explanation.
thanks!
good one
hi kevin, this is realy an amazing video but i got a doubt. can someone tell me is this is applicable for more then two different character's in a string?
Excellent video, I too had a similar approach but I messed the implementation up :( ,
btw the compile-time error part was hilarious, one simply can't get a Java program up and running in one go😂😂😂
*Never laughed so hard watching a programming video!!!*
Bro, there is no way that I could think of this solution on my own..
YOU CAN DO IT!!!!
lol no one can think of these solutions independently in an interview. The whole point is memorization.
@@helloiam2mas Not memorization but understanding!
@@user-id1rf9zb4x understanding comes "after" memorization. Check out the book "Moonwalking with Einstien"
@@GauravBoraJodhpur Shit! what a good book. Gonna check it out thanks!
thanks kevin!! video is helpful.
happy to hear it and anytime :)
Every now and then I get a medium question that kicks my ass. Fuck this question.
Now you though, you're awesome!
well explained
This question was in my JPmorgan test
Great explanation ! Can you please also do distribute the coins in a binary tree ?
great work Kevin, I really enjoy your videos, Can you have a link in the description to your github solution as well
thanks! Check out this repo I have still haven't put all my solutions there though so just a heads up: github.com/kdn251/interviews
amazing explanation
Weibang Zhang thanks :)
Yayyyyyy..😂😂😂
How do I view PPT files on the website using the Django framework?
You have Run button as well 😂😂😂
Hi Kevin , quick question on the maxHeap. In the example "aabbc", count of a is 2 and b is 2 and c is 1. While iterating maxHeap, it removes a and b on first iteration. Now the count is 1 for a,b,c . Now how does the heapMap ensure last added character to the string which is "b", is not retrieved from MapHeap next time since count of all a,b,c is 1. Does heapMap maintains any order if the values are same?
An element of higher priority is processed before any element of lower priority. two elements with same priority are processed according to the order in which they were added to the queue.
Suppose a and b both have frequency 2 initially then after first iteration string can be ab so in next iteration both are left with 1 frequency each then priority can give a or b anything as both have same frequency so if it gives b then string become invalid as abb is not valid..But your program is still working correctly...Can you tell in which fashion does the priority queue work if both have same frequency?
i have the same doubt..
Hey Kevin! Nice and clean approach.
About the runtime complexity, you took heap creation to be O(n), and removing all characters from heap to be O(n log n).
To this, I'd say all the heap operations are O(1) since the alphabet is of size 26. Our heap can't have more than 26 elements at anytime (irrespective of the size of the string S).
So, the overall complexity should be O(n).
I think that would be the additional time for heapify up and down while adding or removing operation in the heap which is log n
@@vinay30111990 Heap ops would be O(log n) if there are order of n elements on the heap. But as the heap size can be max 26, heap ops can't be O(log n).
In other words, heap size is independent of the input size.
Is n the length of the string or the number of unique characters in the string?
You are doing great job but I have seen lot of other videos like this but no body tells us some similar question like this which we can practice..It will be really appreciated if you help us in this way also.🙂thnks
I could think of using a frequency map. Then I thought of sorting by frequency. I thought of using a heap. But I didn't believe enough that it would lead me to the solution. I couldn't organise my thoughts well enough to get to the solution. It happens for some of the problems. How to actually get over this and proceed with the intuition? I used to struggle with easy problems when I started 4 months ago. Now I could figure out something after thinking for a good amount of time but not enough to solve completely.
It took me a while to notice he's decrementing the count of each character per iteration.
There is a simpler way to find out whether or not we should return "":
we find the number of occurrences of the most frequent characters. If this number is > (S.size() + 1)/2, return ""; else it's always true.
It's because we can put the most frequent characters in even positions and intersperse the remaining positions with the remaining letters.
Excellent code and very good explanation.
I think that it can also be done using an array as hashmap and sorting it so we have in the last element always the one with more occurrences.. it would work and I THINK that would be O(N) in time complexity and still O(N) in space complexity. However, your solution is more readable in my opinion, but yeah, maybe worths saying that and can be requested in an interview (if im right with that approach).
Cheeers!
Oh but the sort would take O(NlogN) so it would be same. Unless we can have the max without sorting :think:
inspiring me alot.. keep up the good work.. what if i have a doubt, where to ask?
thanks Sumit and if you need help check out my Patreon page: www.patreon.com/KevinNaughtonJr
This solution is O(NlogN) but there exists an O(N) solution (as long as letters in the string are lowercase alphabet). Keep track of a hashmap counts as in this example. Then go through and find the letter with the highest count. Put that letter in every other even position in the array. Continue this until you finish to the end of the array. Since the hashmap is of size 26, finding the max count so far is O(1) resulting in an overall O(N) solution.
I have a problem which is I got stuck in the middle because am not using java, i code using js i feel lost really
Please put rearrange-string-k-distance-apart in ur list. Thanks for amazing video
Amazing explanation. Love your posts on LinkedIn Kevin,
what will be the time complexity of this approach ?
I was wondering why not use heap.poll() instead of remove() ?
If there are only 26 possible characters, I wonder if you could use Array instead of HashMap?
How do we do that in C#, C# does not have priority queue?
why building the maxheap is O(n) instead of O(nlogn)????
How do you make sure that the element stored as next of one iteration won't be same as current of next iteration? ...Actually I am not aware of what happens if two elements have same priority in a priority queue.
Not sure I follow the algorithm. If we've a string with 3 recurring letters, e.g. sssababab, would this algorithm be spinning on 2 of the 3 letters spreading them, but leave the 3rd one not spread? Or unless the algorithm constantly reevaluates most frequent and 2nd most frequent... Also, what's considered to be the difficulty level of this problem? Easy, medium, hard?
Can you also do maximal rectangle of binary matrix, that one is a dooozy
Brian Goldfarb I’ll put it on the list
Would anyone be so kind as to explain in detail how the line: (a, b) -> counts.get(a) - counts.get(b) works?
I understand that it's picking the higher of the two values but I don't quite understand how the syntax works. Thanks!
It's a lambda expression.
Correct if I am wrong about the runtime
1) the TC of adding all char to map is O(n) ---> N being total char in the string
2) TC for creating heap is O(NLogN) ---> N being total (distinct) char in map
3) while loop --> TC is again O(NLogN) ---> N being total (distinct) char in heap (removing and adding chars for all chars in the heap)
4) so the total is O(n) + O(2NlogN) ---> which becomes O(n + NlogN)
why is the while loop --> TC is again O(NLogN) instead of O(N)?
@@sophiezhang6516 Because we are removing and inserting back the chars into the heap N times. And removing and inserting elements in heap takes LogN time
The video was kick-ass and smooth until I heard "So you want to be a software engineer?" ad :p
Got this question in Microsoft interview and wish I had seen this before. hmm
@Kevin Naughton Jr. There is one important point which is missed in this video.
Current char has to be always inserted first before the next char in the heap .If we change the order of insertion it will start giving wrong answer and the resason is obvious
Huh? No it won't. You don't need to insert element in a heap in any order. The max element will rise to the top upon insertion to preserve heap property. Same with deletion. So I don't see why order of insertion matters.
Curious to hear your perspective.
how is last character guaranteed to not be the same as previous insert?
Good explanation! Except on the time complexity I think you made a mistake. Building the heap will actually cost us n log n (not N), removing from the heap costs log n, which is not the bottleneck though.
Total time complexity: O n log n ( thats what you said, but the reasoning was false)
I thought the same but after doing some digging I found that building a heap is actually O(n) you can see the proof here www.geeksforgeeks.org/time-complexity-of-building-a-heap/ . Cheers
Hey Kevin, I love your videos, just asking curiously, do more optimal solutions exist for these questions that you solve ? For instance, this solution takes O(n log n) time and O(n) space, can we do better than this ? Please do reply :-)
Getting an error about adding the keyset to the PQ
error: incompatible types: Set cannot be converted to Character
pq.add(hm.keySet());
You probably want .addAll()
How do you come up with greedy solutions? Greedy solutions are intuitive but proving that they would work is really tough
can we expect this type of question for a software dev. internship?
I think it's prob fair game for either
The most confusing thing is how the question is phrased in the leetcode.
Y can't we take minimum of most occurring and 2nd most occuring char and build 2*min length string at a time.
This avoids so many additions into heap
Correct me if i am missing anything
If you start from the minimum most occurring, you will be left with more than one character adjacent to one another.
CAN SOMEONE PLEASE EXPLAIN HOW HE MADE THAT PRIORITY QUEUE INTO A MAX HEAP:
THAT LOOKS LIKE LAMBDA EXP.BUT I CANNOT UNDERSTAND.
I think its because he multiplies the count by -1. So if you have something that occurs 4 times in a list, its "count" is -4. So if it is the smallest element, it will be at the top of the tree in a min heap. Then if you pop it, it is the first element out.
It's a lambda expression that overrides the "compare" method of the comparator variant of the constructor. The "b" - "a" expression is using the counts from the map to sort with the characters being put in descending order.
(If someone reads this, pls explain)
How do we make sure that when we are calling heap.remove for getting next char, it is not same as current char
Example : "aaaacdghcjk". When fetching next and current char based on frequency. It will always be 'a'
So in this case, freq of "a" is 4, everything else is 1. After this everything will be put in a max heap.
When you call getMax on this heap, the answer will be "a", and then count is 4. Then you remove "a", so it is no longer present in the heap. What is the next max in the heap? It can't be "a" because it was removed
@@kevinhoxha240 Hey thanks Kevin, got it now. My confusion was that when polling the most frequent character we are just reducing the frequency of the character by 1, but we are actually removing the character from priorityqueue and adding it back later
Thanks for reply. This helped me
Thank you for the video. Got it in one go. Leetcode solution page for this problem is really bad
Anytime!If you need help with more questions like this and like my explanations check out the interviewing service I created thedailybyte.dev/?ref=kevin I'd recommend joining the annual tier if you can!
Kevin Naughton Jr. super, thanks a lot
Harkirat Saluja anytime!
Couldnt we just compare the lengths of most frequent and next most frequent? If they differ by more than one then it wont work and we return false?
PriorityQueue maxheap=new PriorityQueue((a,b)->counts.get(b)-counts.get(a)) PLZ explain what is the meaning of this line. (i knw the Priority Queue and Hash Maps )
Can u pls do the critical connections question from leetcode? Thanks in advance.
it's on my list don't worry
Just a quick update. Now the Leetcode has updated the test cases so in the test case ""abbabbaaab"" where there are multiple characters with same frequency the algo will fail. So just a slight improvement is needed in the comparator of maxHeap that takes into account the ordering of characters.
import java.util.HashMap;
import java.util.PriorityQueue;
class Solution {
public String reorganizeString(String S) {
HashMap map = new HashMap();
PriorityQueue pq = new PriorityQueue((ch1, ch2) -> (map.get(ch1) == map.get(ch2)) ? ch1 - ch2 : map.get(ch2) - map.get(ch1));
for (char ch : S.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (char ch : map.keySet()) {
pq.add(ch);
}
StringBuilder sb = new StringBuilder();
while (pq.size() > 1) {
Character ch1 = pq.remove();
Character ch2 = pq.remove();
sb.append(ch1);
sb.append(ch2);
if (map.get(ch2) > 1) {
map.put(ch2, map.get(ch2) - 1);
pq.add(ch2);
}
if (map.get(ch1) > 1) {
map.put(ch1, map.get(ch1) - 1);
pq.add(ch1);
}
}
if (!pq.isEmpty()) {
char ch = pq.remove();
if (map.get(ch) > 1) {
return "";
} else {
sb.append(ch);
}
}
return sb.toString();
}
}
Thanks!
the code in the video works fine for the above test case you have mentioned
@@sandeeprajurs1994 No, it does not I have checked it.
@@prakharagarwal6237 even today in leetcode it still works. not sure if you miss something
Great explanation. One nit-pick I have is that you should use the Interface "Queue" instead of using the concrete implementation (PriorityQueue) to declare the heap.
really nice code
in Java
Can I just use new PriorityQueue(Collections.reverseOrder())?
We are arranging on the basis of frequency of character ? I don't think this will work.
I think you can do that but then somehow have to also pass a comparator so the heap knows how to organize elements
I dont think so. cause we want our Character order by the its Count not the Character itself, and the value of count of character is in the counts map. So the Comparator with map of counts need to passed.
@@pigflying4514 Right yeah we need both i.e. 1. a max heap and 2. a comparator
well, this one was a little awkward!! haha