Queue Reconstruction by Height | Leetcode

  Рет қаралды 26,262

Techdose

Techdose

Күн бұрын

This video explains a very important programming interview problem which is to reconstruct a given queue based on height and rank parameters.This is a very good hybrid sorting and searching problem.We need to sort the array using a comparator function which sorts based on both height and rank.After sorting, we need to place all the persons starting from least height to their correct position and queue which results in the proper answer queue reconstructed from the given input queue.I have explained the intuition and approach using examples and at the end of the video,i have also shown the code walkthrough. CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
=================================================================
INSTAGRAM: / surya.pratap.k
LinkedIn: / surya-pratap-kahar-47b...
=================================================================
CODE LINK: gist.github.co...
OTHER PROBLEM:-
Implement Queue using Stack (with Example): • Implement Queue using ...
Candy distribution problem: • Candy distribution pro...

Пікірлер: 111
@rishabhkumar8115
@rishabhkumar8115 2 жыл бұрын
Time: O(n^2) it enough for the interview but we can also solve it in O(nlogn) by using binary indexed tree.
@codingwithanonymous890
@codingwithanonymous890 2 жыл бұрын
how?
@ashishm8850
@ashishm8850 4 жыл бұрын
Excellent explanation. It's a pity I did not discover your channel sooner!
@techdose4u
@techdose4u 4 жыл бұрын
Thanks
@thiyagarajanr225
@thiyagarajanr225 4 жыл бұрын
Solving a problem needs a great idea not only programming skills . A great approach to a problem + Programming skills caring about time and space complexities makes us happy people !!! You showed in every aspect bro!!
@techdose4u
@techdose4u 4 жыл бұрын
Thanks bro :)
@yitingg7942
@yitingg7942 3 жыл бұрын
It's very hard to grasp this concept.. I am just not smart enough. sigh...
@techdose4u
@techdose4u 3 жыл бұрын
Even after watching the video ?
@yitingg7942
@yitingg7942 3 жыл бұрын
@@techdose4u Yes Sir, for some reason today is extremely hard.
@techdose4u
@techdose4u 3 жыл бұрын
@@yitingg7942 then let me know in msg. I will help you :)
@ГеоргийМай-т3в
@ГеоргийМай-т3в 4 жыл бұрын
Unfortunately I gave up on my own decision :( thank you for great explanation. It seems equal-height elements we can sort in descending order (for k value), so that while insertion in new array people with equal height won't meet each other so lines 26-33 can look just a little bit more simple: if (ans[j][0] == -1) { if (count == 0) { ans[j] = people[i]; break; } else --count; }
@techdose4u
@techdose4u 4 жыл бұрын
Welcome
@sahilchoudhary1473
@sahilchoudhary1473 4 жыл бұрын
sir your content is amazing and easy to learn cloud you please make videos on leetcode weekly and Biweekly contests this will help us a lot to learn more
@techdose4u
@techdose4u 4 жыл бұрын
Bro I am busy with this leetcode contest. I want to quickly get this over with 😅
@gauravmasand
@gauravmasand 18 күн бұрын
Ok better optimal solution class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people = sorted(people, key=lambda x: (-x[0], x[1])) ans = [] for person in people: ans.insert(person[1], person) return ans Try this with O(N log N) time complexity and easy to do in cpp also try it by ur self
@ashishchoksi8501
@ashishchoksi8501 4 жыл бұрын
insted of this for simplicty of code we traverse array from end and use arr.insert(arr.begin()+pos[i], height[i]);
@shwetanksingh5438
@shwetanksingh5438 4 жыл бұрын
I wait for your editorials to get deep insight.
@techdose4u
@techdose4u 4 жыл бұрын
Nice :)
@praveenchouhan6388
@praveenchouhan6388 4 жыл бұрын
even same case with me, excellent workkkk!!!!!!
@kSERITIKGupta
@kSERITIKGupta 2 жыл бұрын
Can anyone explain why this condition was added *else if(ans[j][0]==-1 || ans[j][0]>=people[i][0]) count-=1;*
@PurpleDaemon_
@PurpleDaemon_ 2 жыл бұрын
Thanks for the explanation! But I must warn the rest of the viewers, that there is a much more optimal and compact solution with sorting in descending order and a simple push (insert in Python or a linked list in Java).
@harinaaraayans3453
@harinaaraayans3453 4 жыл бұрын
nice explanation .. we can solve it with the same time complexity by starting from the tallest persons first and using a linked list
@techdose4u
@techdose4u 4 жыл бұрын
Yes correct :)
@MrKB_SSJ2
@MrKB_SSJ2 Жыл бұрын
I LITERALLY TRIED THE SAME APPROACH DAMMIT BUT YET GOT INCORRECT ANSWERS.
@akshatjain6854
@akshatjain6854 4 жыл бұрын
Bro make a video on Minimum Swaps To Make Sequences Increasing
@techdose4u
@techdose4u 4 жыл бұрын
This month I am busy with leetcode discussions bro.
@akshatjain6854
@akshatjain6854 4 жыл бұрын
@@techdose4u This leetcode 30 days challenge will keep on coming. But pls make a video on some very imp problems
@spetsnaz_2
@spetsnaz_2 4 жыл бұрын
you can check this one : www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/ or www.geeksforgeeks.org/minimum-number-of-swaps-required-to-sort-an-array-set-2/?ref=rp
@indraalapati989
@indraalapati989 4 жыл бұрын
Java solution - public int[][] reconstructQueue(int[][] people) { /* Step1 - sort people based on heights in descending order, if heights are equal sort on basis of position in ascending order. Step2 - after sorting, arrange people at output index based on their position */ Arrays.sort(people, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0]); List list = new ArrayList(); for(int[]p : people){ list.add(p[1], p); } int n = people.length; return list.toArray(new int[n][2]); }
@techdose4u
@techdose4u 4 жыл бұрын
👍
@Safar_Ayushi_Ka
@Safar_Ayushi_Ka 4 жыл бұрын
How can I improve the concepts on time and space complexities? Let me know plz
@techdose4u
@techdose4u 4 жыл бұрын
Please solve MCQ questions on time and space or else read some codes and try to figure out the time and space and then see the editorial answer. This way you will learn. Follow geeks. They have time and space mentioned for each code at the end.
@Safar_Ayushi_Ka
@Safar_Ayushi_Ka 4 жыл бұрын
@@techdose4u thanks
@akshatjain6854
@akshatjain6854 4 жыл бұрын
was waiting for your video
@techdose4u
@techdose4u 4 жыл бұрын
👍 Solved already?
@akshatjain6854
@akshatjain6854 4 жыл бұрын
@@techdose4u No it was kind of hard, I sorted it and didn't get what to do next
@techdose4u
@techdose4u 4 жыл бұрын
Okay...now you do :)
@kishankumargupta4200
@kishankumargupta4200 4 жыл бұрын
​@@techdose4u Even if I solve the problem, I come to watch your videos for optimized version or new approach. Your approach to solve the problems are very helpful. Keep making videos :)
@techdose4u
@techdose4u 4 жыл бұрын
Thanks bro :)
@nishantsharma3100
@nishantsharma3100 4 жыл бұрын
i solved this one using new array . by placing the smallent the smallest first and then placing the second smallest and so on . worked fast too.
@techdose4u
@techdose4u 4 жыл бұрын
Yes. This is the same approach given in hint and I explained it too :)
@namanjain9094
@namanjain9094 3 жыл бұрын
@@techdose4u Bro you should always post the optimized approach as by this approach interviewer will not be happy and will ask to optimized it and then what we will do ..... so you should always post optimized approach (in this case using segment tree) and thus not make fool of students following you. Hope you take this seriously as this is serious because there would be absolutely no gain In seeing your approach as the interviewer will definitely want an optimized approach and we would be stuck there. So please consider this seriously.
@thunderbolt8632
@thunderbolt8632 4 жыл бұрын
Absolutely love your work sir!👍 Btw do you work at FAANG?
@techdose4u
@techdose4u 4 жыл бұрын
No
@thunderbolt8632
@thunderbolt8632 4 жыл бұрын
@@techdose4u Oh got u,SAMS😅
@techdose4u
@techdose4u 4 жыл бұрын
🤣
@willturner3440
@willturner3440 3 жыл бұрын
@@techdose4u but you have good knowledge of dsa
@AbhishekKumar-gg6ox
@AbhishekKumar-gg6ox 4 жыл бұрын
How did you you understood the goal of the question ??There was nothing mentioned in the problem statement.
@techdose4u
@techdose4u 4 жыл бұрын
If you read the question repeatedly with given example then you can figure it out. I also tried some inputs and saw the expected output. That's another technique on leetcode.
@Learner010
@Learner010 4 жыл бұрын
sorry , to say but i don't get it fully with reasons of why! maybe more illustration is good for this kind of problem.
@techdose4u
@techdose4u 4 жыл бұрын
I explained it well enough. You should try to rewatch it attentively. Actually we are sorting because when we are processing from shortest height and we are putting elements at correct position. While doing so, we are skipping some blank spaces on the basis of how many will be greater than the given element. We know that all the future elements will be >= curr element and so we can make the decision of whether to skip the current blank space of not. That's the reason :)
@siddharthsingh9409
@siddharthsingh9409 4 жыл бұрын
i'am new with coding and don't know where to start......guide me where i can start solving problem and some time when i stuck its really feel bad so tell me where i can see solution>> nice explanation of above videos.
@techdose4u
@techdose4u 4 жыл бұрын
You can start with reading editorials for easy level problems and try to solve them or implement the read idea. Once you get confident in easy level questions, move ahead.
@pwnweb5734
@pwnweb5734 Жыл бұрын
Greedy problems are just ;/
@spetsnaz_2
@spetsnaz_2 4 жыл бұрын
Very good explanation... Earlier I couldn't figure out why people were using count. Now it makes sense
@techdose4u
@techdose4u 4 жыл бұрын
👍
@abhishekkumardwivedi3817
@abhishekkumardwivedi3817 4 жыл бұрын
Thanks a lot, your videos are lot more helpful and explanation is also awesome and the choice of questions is also very good please do solve some more questions of the same or more hard level.
@techdose4u
@techdose4u 4 жыл бұрын
👍
@rohitbose405
@rohitbose405 2 жыл бұрын
please do with segment tree
@tejaswigutta9017
@tejaswigutta9017 4 жыл бұрын
@TECH DOSE when we solve a particular problem,how can we find similar questions applying similar logic with little modifications?
@techdose4u
@techdose4u 4 жыл бұрын
Leetcode will recommend otherwise I don't know the correct method to find very specific type problem.
@nishantsharma3100
@nishantsharma3100 4 жыл бұрын
in the problem description there is a option below the question saying similar questions .
@manojg4451
@manojg4451 3 жыл бұрын
Beautiful Explanation!
@techdose4u
@techdose4u 3 жыл бұрын
Thanks
@toekneema
@toekneema 3 жыл бұрын
This should be a HARD question
@techdose4u
@techdose4u 3 жыл бұрын
Right
@bhaskary2362
@bhaskary2362 2 жыл бұрын
If we sort the elements with same heights in descending order of no. of people ahead of them then we don't need to check count for >= we would only need to count empty spaces.
@TheTatsi100
@TheTatsi100 4 жыл бұрын
It is the best explanation, very clear. Thanks
@techdose4u
@techdose4u 4 жыл бұрын
Thanks :)
@faangsde
@faangsde 4 жыл бұрын
While (publishing_video): print(" Awesome videos! Thanks 🌟🌟🌟")
@nagajaswanth831
@nagajaswanth831 4 жыл бұрын
solved it in python:)) class Solution(object): def reconstructQueue(self, people): people.sort() x=[0 for i in range(len(people))] for i in people: h=i[0] k=i[1] c=0 for j in range(len(x)): if x[j]==0: c+=1 elif x[j][0]==h: c+=1 if c==k+1: x[j]=[h,k] break return x
@RitikKumar-cx5wf
@RitikKumar-cx5wf 4 жыл бұрын
Sir, please help me to solve this question(when I use -1 for intialize for front and rear(-1) then it give me error but when I use (0) for intialize front and rear then it give me right answer ) // find largest multiplication of 3 no. Of array like {8,1,9}=>{9, 8,1}; Sir, please check my code // find largest multiplication of 3 by queue #include #include struct queue{ int front; int rear; int capacity; int *array; }; void enqueue(struct queue** q, int data){ if((*q)->rear+1==(*q)->capacity) return; else{ (*q)->array[(*q)->rear]=data; // printf(" %d",(*q)->array[(*q)->rear]); (*q)->rear=(*q)->rear+1; } } int dequeue(struct queue** q) { if((*q)->front==-1&&(*q)->rear==-1) return; int data=(*q)->array[(*q)->front]; for(int i=(*q)->front;irear-1;i++) (*q)->array[i]=(*q)->array[i+1]; (*q)->rear=(*q)->rear-1; // printf(" %d",(*q)->rear-1); // printf(" Dequeue=%d",data); return data; } int front(struct queue** q){ if((*q)->rear==-1&&(*q)->front==-1) return; return((*q)->array[(*q)->front]); } void push(struct queue** q,int data){ int extract; if((*q)->front==-1&&(*q)->rear==-1){ (*q)->front=0;(*q)->rear=0; enqueue(q, data); return; } else{ int temp=front(q); if(datafront;indexrear;index++) printf(" %d",q->array[index]); } struct queue* createqueue(int cap){ struct queue* q=(struct queue*)malloc(sizeof(struct queue)); q->rear=-1;q->front=-1; q->capacity=cap; q->array=(int*)malloc(cap*sizeof(int)); return q; } void main(){ int arr[3]={8,9,1};int index;int n=3; struct queue *q=createqueue(3); // q1.rear=-1;q.front=-1;q.capacity=-1; for(index=0;index
@harshpatel1385
@harshpatel1385 4 жыл бұрын
Always great explanation. Can you explain bride hunting problem? .which is asked in tcs codevita. It is my request. I am watching your regular.
@techdose4u
@techdose4u 4 жыл бұрын
This month I am busy with this leetcode discussions. I will see that bride hunting problem. Is it accessible to everyone?
@harshpatel1385
@harshpatel1385 4 жыл бұрын
@@techdose4u yes .it is accessible to everyone.
@harshpatel1385
@harshpatel1385 4 жыл бұрын
I know you putting to much effort. Next month codvita will be conducted.from all over India lots of student participated in it.if you put previously asked questions's solution then it beneficial for them to clear exam and they can get good package . This my suggestion sir .
@techdose4u
@techdose4u 4 жыл бұрын
Yes I want to help everyone. But if I do that then I will miss this leetcode where I have already committed. That is why I am not able to add anything else 😅 I will try to do it if possible.
@spetsnaz_2
@spetsnaz_2 4 жыл бұрын
Can you share the code link here :-)
@randomrandom316
@randomrandom316 4 жыл бұрын
For someone looking for Python solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: n = len(people) people.sort(key=lambda x:x[0]) ans = [None]*n for pair in people: counter = pair[1] for index, item in enumerate(ans): if item is None: if counter==0: break else: counter-=1 else: if item[0]>=pair[0]: if counter==0: break else: counter-=1 ans[index] = pair return ans *This is not an optimum way of doing this rather a brute force approach.*
@thallapakuteja2350
@thallapakuteja2350 4 жыл бұрын
are u giving solutions on ur own ? where do u work
@techdose4u
@techdose4u 4 жыл бұрын
On my own means? Please follow linkedIn
@thallapakuteja2350
@thallapakuteja2350 4 жыл бұрын
@@techdose4u thinking solution with ur brain without other help ur linked in id
@techdose4u
@techdose4u 4 жыл бұрын
Check video description or else channel page.
@dheerajpoonia2175
@dheerajpoonia2175 4 жыл бұрын
@techdose4u
@techdose4u 4 жыл бұрын
@shabarishthamme445
@shabarishthamme445 4 жыл бұрын
Sir why can't we sort based on values after storing given 2D array in map.
@ShaliniNegi24
@ShaliniNegi24 4 жыл бұрын
Can We have more efficient algorithm ?
@mohdaasimqureshi7115
@mohdaasimqureshi7115 2 жыл бұрын
Great Explanation 🙌🙌
@babbarutkarsh7770
@babbarutkarsh7770 4 жыл бұрын
Best explaination ever !!!
@techdose4u
@techdose4u 4 жыл бұрын
Thanks babbar :)
@namanjain9094
@namanjain9094 3 жыл бұрын
@@techdose4u Bro you should always post the optimized approach as by this approach interviewer will not be happy and will ask to optimized it and then what we will do ..... so you should always post optimized approach (in this case using segment tree) and thus not make fool of students following you. Hope you take this seriously as this is serious because there would be absolutely no gain In seeing your approach as the interviewer will definitely want an optimized approach and we would be stuck there. So please consider this seriously.
@cocoarecords
@cocoarecords 4 жыл бұрын
best thanks
@avikmallick2493
@avikmallick2493 3 жыл бұрын
Can't it be done in O(n) or O(nlogn)?
@namanjain9094
@namanjain9094 3 жыл бұрын
@TECH DOSE Bro you should always post the optimized approach as by this approach interviewer will not be happy and will ask to optimized it and then what we will do ..... so you should always post optimized approach (in this case using segment tree) and thus not make fool of students following you. Hope you take this seriously as this is serious because there would be absolutely no gain In seeing your approach as the interviewer will definitely want an optimized approach and we would be stuck there. So please consider this seriously.
@namanjain9094
@namanjain9094 3 жыл бұрын
Yes this approach is fully wrong there is much optimization that could be done (use segment tree) See gfg
@shrad6611
@shrad6611 4 жыл бұрын
question ka link daal diya karo bhai
@techdose4u
@techdose4u 4 жыл бұрын
Question number is already present.
@shrad6611
@shrad6611 4 жыл бұрын
but it is easy for your user to go and solve it first if url is present btw great video sir
@priyankahegde6441
@priyankahegde6441 4 жыл бұрын
Sir, can't we sort it based on number of people to be on left side, and if it's equal then sorting based on the height?
@techdose4u
@techdose4u 4 жыл бұрын
I don't think this will work because a person with lower height doesn't effect the one with higher height
@anuragtiwari5396
@anuragtiwari5396 4 жыл бұрын
i took the opposite approach of starting with the tallest person. My approach works because of the fact that if you insert a smaller person to the left of a tall person then it won't affect the order . class Solution { public: vector reconstructQueue(vector& people) { sort(people.begin(),people.end(),compareInterval); //sort the vector vector res; for(int i=0;ibrr[0])? true:(arr[0]==brr[0])?((arr[1]
@CollectConnectDots
@CollectConnectDots 4 жыл бұрын
Java Solution - github.com/neeraj11789/tech-interview-problems/blob/db63845ae0a24835f9edc8703e268d146cfa56d4/src/main/java/leetcode/junechallenge/QueueReconstructionByHeight.java
@BoobalanMunusamy
@BoobalanMunusamy 4 жыл бұрын
Coming up with your own solution is good, but people will raise the concerns when it is not an optimized one. After, submit your solution in leetcode, you may check with other's answers before making the video. Otherwise, you may lose the subscribers. This can be solved in O(nlogn +n) class Solution { public int[][] reconstructQueue(int[][] people) { List result = new ArrayList(); Arrays.sort(people, new Comparator() { @Override public int compare(int[] x, int[] y) { return x[0] == y[0] ? x[1] - y[1] : y[0] - x[0]; } }); for(int[] person : people) { result.add(person[1], person); } return result.toArray(new int[result.size()][]); } }
@techdose4u
@techdose4u 4 жыл бұрын
Your solution is N2. Adding elements to dynamic array is O(N) per element (don't know about java but it is true for C++) and no solution on Leetcode discussions is below N2. They did not consider the dynamic array insertion time which is O(N).
@vishalambhore4508
@vishalambhore4508 4 жыл бұрын
​ TECH DOSE I agree this not nlogn solution but yes there is solution which run in o(nlogn) .
@anujraj6370
@anujraj6370 4 жыл бұрын
Time complexity can be significantly reduced to N*log^2N by using a Fenwick tree and doing a binary search.
Surrounded Regions | Leetcode #130
13:30
Techdose
Рет қаралды 28 М.
HAH Chaos in the Bathroom 🚽✨ Smart Tools for the Throne 😜
00:49
123 GO! Kevin
Рет қаралды 16 МЛН
🍉😋 #shorts
00:24
Денис Кукояка
Рет қаралды 3,5 МЛН
Fastest Way to Learn ANY Programming Language: 80-20 rule
8:24
Sahil & Sarra
Рет қаралды 868 М.
Interval List Intersections | Leetcode #986
12:19
Techdose
Рет қаралды 24 М.
Coin Change 2 | Dynamic programming | Leetcode #518
20:32
Techdose
Рет қаралды 55 М.
Leetcode - Queue Reconstruction by Height (Python)
6:28
Timothy H Chang
Рет қаралды 1,3 М.