2 Kth Smallest Element

แชร์
ฝัง
  • เผยแพร่เมื่อ 24 ธ.ค. 2024

ความคิดเห็น • 225

  • @naweliverma5484
    @naweliverma5484 3 ปีที่แล้ว +47

    Kabhi itne awesome tarike se kisi ne samjahya hi nai. :D

  • @NotNotNithin
    @NotNotNithin 3 ปีที่แล้ว +152

    In Java, by default, it is a min-heap.
    Min Heap:
    PriorityQueue minHeap = new PriorityQueue();
    Max Heap: Using comparator to make it a max heap.
    PriorityQueue maxHeap = new PriorityQueue((a, b) -> b - a);
    Updated Java code:
    private static int findKthSmallestElement(int[] arr, int k, int size) {
    PriorityQueue maxHeap = new PriorityQueue((a, b) -> b - a);
    for (int i = 0; i < size; i++) {
    maxHeap.add(arr[i]);
    if (maxHeap.size() > k) {
    maxHeap.poll();
    }
    }
    return maxHeap.peek();
    }

    • @varshityadav5467
      @varshityadav5467 3 ปีที่แล้ว +22

      thanks bhai bacha liya tune idhar udhar bhatakne se

    • @56sanjivanisingh58
      @56sanjivanisingh58 3 ปีที่แล้ว +2

      thankyou so much

    • @pawanmaurya8300
      @pawanmaurya8300 3 ปีที่แล้ว +3

      @@varshityadav5467 I just also came to check this 😅

    • @YogeshShinde31
      @YogeshShinde31 2 ปีที่แล้ว +4

      FYI..Comparator can be Comparator.reverseOrder() for maxheap of Integer.

    • @kuchettisantoshkumar65
      @kuchettisantoshkumar65 2 ปีที่แล้ว +17

      PriorityQueue maxHeap = new PriorityQueue(Collections.reverseorder());
      This can also be used and very easy to remember for a beginner.

  • @hritwiksom3032
    @hritwiksom3032 4 ปีที่แล้ว +50

    If we use MaxHeap, we have O(k) space and O(nLogk) time.
    If we use MinHeap, we have O(1) space and O(n + klogn) time.
    If k is small such that k~logk,
    MinHeap gets reduced to ~O(n + logn)
    MaxHeap gets reduced to ~O(n)
    If k is of the order n,

    • @dipeshsaili4468
      @dipeshsaili4468 2 ปีที่แล้ว +1

      what is quick select method?

    • @whysoserious-yj1ku
      @whysoserious-yj1ku 2 ปีที่แล้ว

      Can you explain what is the problem with the quickselect method if there are repeated elements?
      I just submitted the quickselect method in a problem having test cases with repeated elements and it passed all test cases.

  • @Samtoosoon
    @Samtoosoon 4 หลายเดือนก่อน +2

    Priority -queue

    • @Samtoosoon
      @Samtoosoon 4 หลายเดือนก่อน

      Min big

  • @shiva_krishna_rama
    @shiva_krishna_rama 4 ปีที่แล้ว +71

    The time complexity of priority_queue to insert one element is O(logk) so inserting "k" element will take
    O(klogk) and (n-k) element are remaining to insert will take (n-k)logk time so total time complexity is
    T = klogk + (n-k)logk
    T = klogk + nlogk -klogk
    T = nlogk
    Very Nice, I got it And I liked it , Thank You bhaiya

    • @abhinavsharma3819
      @abhinavsharma3819 4 ปีที่แล้ว +2

      I think there is a correction required.
      worst case time complexity for k elements is k(logn), and for n-k it will be (n-k)log(n) , TOtal will be nLogn, which is the complexity of insertion of full array in a heap.
      It will be equal to merge-sort only, nothing less

    • @shiva_krishna_rama
      @shiva_krishna_rama 4 ปีที่แล้ว +1

      @@abhinavsharma3819
      no bro,
      time complexity of inserting in Priority_queue of size k is logk in worst case so,time comp. inserting n elements in k size is nlogk
      p_queue

    • @shrinathdeva6997
      @shrinathdeva6997 4 ปีที่แล้ว +3

      Well actually the worst case complexity is still nlogn only as in the worst case k = n. Hope you get why the worst case complexity is not nlogk

    • @manishkumar-qn6lx
      @manishkumar-qn6lx 4 ปีที่แล้ว +1

      @Nahrma Bozonda
      Thanks for such beautiful explanation.

    • @utpalpodder-pk6vq
      @utpalpodder-pk6vq 4 ปีที่แล้ว +6

      @@shrinathdeva6997 the tree size never go beyond logK so processing N elements in worst case requires O(NlogK) time

  • @viralprajapati485
    @viralprajapati485 3 ปีที่แล้ว +1

    Arre bhai aap kya smjate ho yaar..gajab... Aapne ek dost ki tarah samjaya..Maja aagaya

  • @santokhsingheng
    @santokhsingheng 4 ปีที่แล้ว +11

    Thanks Bhai!! you are doing an amazing work. Looking forward for backtracking videos.

  • @NikitaGulabani
    @NikitaGulabani ปีที่แล้ว +15

    I love your video, it makes learning so easy. Why have you stopped making them ? Can you please create videos on Graphs, Tree and Trie as well

  • @abhishek.rathore
    @abhishek.rathore 3 ปีที่แล้ว +2

    Kya samajhaya hai bhai, gfg ke solutions to bilkul samajh nahi aa rahe the. Thanks a lot!!

  • @ishigupta2649
    @ishigupta2649 4 ปีที่แล้ว +11

    Sir ur video are very very helpful..thnkuhh sirr.....sir backtracking nd branch nd bound ki bhi upload kr dijeea sir video plzz

  • @shailajasharma1515
    @shailajasharma1515 4 ปีที่แล้ว +3

    Thank you so much sir, I am able to understand your videos clearly, you makes the concept very easy to understand, i have implemented this in java, here is my code,
    //Approach 2: Using Max Heap
    public class KthSmallestElementInArray {
    static PriorityQueue maxHeap;

    static public int findKSmallestElem(int arr[], int k) {

    for(int a: arr) {
    maxHeap.add(a);
    if (maxHeap.size() > k) {
    maxHeap.poll();
    }
    }
    return maxHeap.peek();
    }

    public static void main(String[] args) {
    int arr[] = {8, 9, 5, 2, 6, 7};
    int k = 2;

    System.out.println("Original Array is: " +Arrays.toString(arr));

    maxHeap = new PriorityQueue(Collections.reverseOrder());

    int ksmallelem = findKSmallestElem(arr, k);


    System.out.println("Kth Smallest Element is: " + ksmallelem);

    }
    }

    • @indranilthakur3605
      @indranilthakur3605 4 ปีที่แล้ว

      Where did you learn Heap? I am trying to find a good resource but not able to get one.

  • @piyushsaxena6243
    @piyushsaxena6243 4 ปีที่แล้ว +3

    Thanks a lot for these helpful videos, please keep on making more such videos sir.

  • @yashagrawal3272
    @yashagrawal3272 3 ปีที่แล้ว +4

    Here the time complexity is reduced but the space required is increased .But when we use merge sort then that same array can be modified .

    • @wttc4
      @wttc4 10 หลายเดือนก่อน

      but in merge-sort, space complexity is O(N) (we use temp array for merging) and here the space is reduced to O(K).
      Please let me know if I've misunderstood.

  • @deepakprajapati5064
    @deepakprajapati5064 4 ปีที่แล้ว +2

    Thank you
    So much easy and understandable explanation 👍

  • @shubh4793
    @shubh4793 3 ปีที่แล้ว +1

    Good work here Aditya. your series is really helping me out.

  • @tanmaysahare2353
    @tanmaysahare2353 2 ปีที่แล้ว

    Superb teaching Bhai

  • @kartikpatidar870
    @kartikpatidar870 3 ปีที่แล้ว

    Aditya bhaiya Great Explanation 🔥

  • @vaibhavgupta2040
    @vaibhavgupta2040 ปีที่แล้ว

    mact ke londo ki tone mai mact jhalakta hai 🔥🔥

  • @anchalpandey2787
    @anchalpandey2787 4 ปีที่แล้ว +3

    7:46
    Input to le hi loge 😂😂
    That was epic

  • @swastibhagora9914
    @swastibhagora9914 3 ปีที่แล้ว +4

    Hi bro, in the interview do they ask us to implement the heap using tree?

    • @may21136
      @may21136 2 ปีที่แล้ว

      It is the same thing.
      In priority queue, you enter elements by binary searching (O(log(k)). In an ordered binary search tree, insertion will also take O(log(k)).
      In priority queue, you pop the top element. Likewise, in tree, you just remove the rightmost leaf node.
      Moreover, C++ STL stores priority queue as a self balancing tree in memory.

  • @kshitijmishra2716
    @kshitijmishra2716 2 ปีที่แล้ว +3

    any gfg or leetcode link for this quesiton ?

  • @bestsaurabh
    @bestsaurabh 4 ปีที่แล้ว +1

    Why we don't have a delete /erase method in priority_queue stl lib? I guess it will O(n) for any. random element delete? Any help

  • @the_haryannvi_coder
    @the_haryannvi_coder 9 หลายเดือนก่อน

    Here, we don't need to push every element in queue. After pushing k elements, compare next n-k with top element if they are greater then top then pop top one and push the current one. This will reduce the complexity. If we push each element then complexity will not be N * log(k).

  • @anchalmishra2322
    @anchalmishra2322 3 ปีที่แล้ว

    your eplanation is really osm sir g

  • @arshaanhusain6573
    @arshaanhusain6573 2 ปีที่แล้ว

    At 4:28 you said that order of 3 and 4 is not important as compared to 10, ok, so if we insert 6 instead of 15 then the order could be 7 ,3,4,6 and then we pop 7, so how do we get 6 as 3rd maximum?

    • @optimus_prime01
      @optimus_prime01 ปีที่แล้ว +2

      vro after popping 7 , 6 will come on top. That's what max_heap do

  • @closer9689
    @closer9689 9 หลายเดือนก่อน

    I have two doubts : 1)The work done by heap here can be done by monotonic stack also?2) bhaiya said here that it is not mandatory for array to be sorted ..Then how can we surely say that the top element is our answer?

  • @anjalirungta9816
    @anjalirungta9816 4 ปีที่แล้ว +3

    Liking ur videos too much.plzz make videos for hashing part also.it will be of great help.

  • @cryptowithfaizan8649
    @cryptowithfaizan8649 3 ปีที่แล้ว +1

    Bhai bahut badiya

  • @syedrizwan2203
    @syedrizwan2203 9 หลายเดือนก่อน +1

    for someone who is searching for java code.
    public class FindKthSmallestElement {
    public static void main(String[] args) {
    int arr[]= {7,10,4,3,20,15};
    int k=3;
    int size=6;
    PriorityQueue maxheap = new PriorityQueue((a,b)-> b-a);
    for (int i = 0; i < arr.length; i++) {
    maxheap.add(arr[i]);
    if(maxheap.size()>3) {
    maxheap.poll();
    }
    }
    System.out.println(maxheap.peek());
    }
    }

  • @ankitgarg5871
    @ankitgarg5871 3 ปีที่แล้ว

    Thanks from toda and my side.😊

  • @harshtita5819
    @harshtita5819 4 ปีที่แล้ว +3

    Bro I tried using this on GFG but it showed TLE. Asked to optimize it.
    Used scanf and printf and still was being asked to optimize.
    Used std::sort() instead of heap and submission was successful. Can you clarify ?

    • @TheAdityaVerma
      @TheAdityaVerma  4 ปีที่แล้ว +7

      gfg is broken 😂

    • @TheAdityaVerma
      @TheAdityaVerma  4 ปีที่แล้ว +7

      btw there is an order of n approach to it using quick sort, you can try it out.
      But if its getting accept using sort and not heap the ide is certainly broken as sorting will have more time complexity.

    • @harshtita5819
      @harshtita5819 4 ปีที่แล้ว +1

      Exactly! I understood that time complexity using heap is much better than using sorting . Anyway, love your content, keep posting videos and help students like us . Thanks 😃

    • @subhamchoudhary9123
      @subhamchoudhary9123 4 ปีที่แล้ว

      but gfg also has O(1) space complexity constraint

    • @harshtita5819
      @harshtita5819 4 ปีที่แล้ว

      If the constraint is O(1) space complexity then only sorting would give the answer and won't show any TLE error otherwise for an optimized time complexity, heap solution is preferred.

  • @shauryasingh8331
    @shauryasingh8331 2 ปีที่แล้ว +1

    if you use heapify method to build heap in order of n time and pop k times then the overall time complexity will bbe n+klogn. Is this method better thn shownin video?why not?

  • @vaibhavpandey5615
    @vaibhavpandey5615 4 ปีที่แล้ว +1

    thankyou aditya bhaiya for this beautiful identification rule.

  • @deepalibajaj9768
    @deepalibajaj9768 4 ปีที่แล้ว

    Sir I need one help u have written to take input size and u are using size function...in heap how it can automatically sort

  • @manikrangar6357
    @manikrangar6357 4 ปีที่แล้ว +1

    sir how the complexity remains nlogk as you push every element once and depending on the conditions pop as well so if i am not wrong total insertion would take nlogn and there are also some deletions so additional xlogn

    • @abhinavsharma3819
      @abhinavsharma3819 4 ปีที่แล้ว

      Exactly my point.

    • @abhinavsharma3819
      @abhinavsharma3819 4 ปีที่แล้ว

      A solution come to my mind.
      When heap.size() becomes k , lets take 4, Means 4 smallest element for present case have been taken already, then just peek() and see if the next element is smaller than the top, accept it, else do not insert
      Outer i loop:
      {
      if h.size()

    • @umanggupta5803
      @umanggupta5803 3 ปีที่แล้ว

      @@abhinavsharma3819 You need to consider all elements in array before declaring the answer

    • @omkarvashistha2400
      @omkarvashistha2400 3 ปีที่แล้ว

      @@abhinavsharma3819 your solution is good to go just one change that in else part before inserting first pop the top element then insert otherwise the answer that we want will be popped

    • @omkarvashistha2400
      @omkarvashistha2400 3 ปีที่แล้ว

      @@umanggupta5803 no it is fine all elements are considered but not all are inserted to queue

  • @GauravKawatrakir
    @GauravKawatrakir 3 ปีที่แล้ว

    Thanks for the video. Appreciate your efforts. One more thing can do like "What are the techniques we can use to solve array based problems"? majorly used technique I mean like heap, two pointers, sliding window, etc. These can help to answer Data structure questions. Techniques are not majorly not know to anyone, people have idea "How to solve problem?" but not aware about techniques How to solve problem?

  • @akhilach6243
    @akhilach6243 ปีที่แล้ว

    Does it works if the array contains duplicate??

  • @archanoidtalks9393
    @archanoidtalks9393 3 ปีที่แล้ว +1

    Sir are we allowed to use stl in interview

  • @ishigupta2649
    @ishigupta2649 4 ปีที่แล้ว

    Sir jsne aapne stl k use kiya h heap m kya hm 2 stack lekr bhi code bna skte h without vector?

    • @debarshibhattacharya9141
      @debarshibhattacharya9141 4 ปีที่แล้ว

      Then we will not get the maximum element on the top every time, so stack is not appropriate here.

    • @lakshmanmohanlanka9334
      @lakshmanmohanlanka9334 4 ปีที่แล้ว

      You can do it using just one stack as well if your sole intention is to have the maximum element on the top of stack

  • @learnhumanity6701
    @learnhumanity6701 2 ปีที่แล้ว

    Hello Sir. Thanks for your video it was a very well-explained video. Can you please upload an explanation for the kth largest odd number in a given range using the greedy approach?

  • @shashankmishra484
    @shashankmishra484 2 ปีที่แล้ว +2

    Hey, do companies expect quick select algorithm for these kind of questions? Or heap will suffice?

  • @poojaupadhyay6364
    @poojaupadhyay6364 4 ปีที่แล้ว

    how can we implement this in java? is there any function equivalent to type def and STL in java,which can be used?

    • @debasmitamishra9992
      @debasmitamishra9992 4 ปีที่แล้ว +2

      Yes.You can use java.util.PriorityQueue.You can use it for both min and max heap.You can see stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue

    • @poojaupadhyay6364
      @poojaupadhyay6364 4 ปีที่แล้ว

      @@debasmitamishra9992 thanks a lot dear!

  • @concnew1420
    @concnew1420 3 ปีที่แล้ว +1

    Gfg pe sort function ka use kar ke accept hogya pr max heap se tle de rha????

    • @deepakkumar-fp8uj
      @deepakkumar-fp8uj 3 ปีที่แล้ว

      nhi nhi de rha, ek baar mein submit ho gya!

    • @concnew1420
      @concnew1420 3 ปีที่แล้ว

      @@deepakkumar-fp8uj bhai code idhar paste kar do

  • @shahanaalam2676
    @shahanaalam2676 3 ปีที่แล้ว +4

    While implementing the same code in gfg practice, it's giving TLE 🙁🙁
    Here's my code:
    // arr : given array
    // l : starting index of the array i.e 0
    // r : ending index of the array i.e size-1
    // k : find kth smallest element and return using this function
    int kthSmallest(int arr[], int l, int r, int k) {
    priority_queue maxh;
    for(int i = 0; i k)
    maxh.pop();
    }
    return maxh.top();
    }

    • @animeshsingh7060
      @animeshsingh7060 3 ปีที่แล้ว +1

      this gfg question tells that all elements are distinct. in case of distinct elements we can use quick select method, which is better.

    • @govindkrishnalb
      @govindkrishnalb 2 ปีที่แล้ว

      it won't show error now, since they have changed the testcases. We could use quick select method but select random pivot. (leave it to the machine)

  • @himanshupednekar
    @himanshupednekar 4 ปีที่แล้ว +6

    In python
    from heapq import heappop, heappush, heapify
    def getKSmallest(arr, k):
    maxheap = []
    heapify(maxheap)
    for i in arr:
    heappush(maxheap, -1 * i)
    if len(maxheap) > k:
    heappop(maxheap)

    return maxheap[0] * -1

    • @Anjalisinghattri
      @Anjalisinghattri 4 ปีที่แล้ว +1

      why used -1*i?? also in return statement

    • @himanshupednekar
      @himanshupednekar 4 ปีที่แล้ว +2

      @@Anjalisinghattri since in python their is no library for max heap, so we need to modify min heap and use it. The modification is to multiple value with -1 and use it, no it will work as max heap, and while returning we need to return original value, so one more time multiply it with -1. Clear??

    • @Anjalisinghattri
      @Anjalisinghattri 4 ปีที่แล้ว

      Ok thankyou

    • @SouravKumar-tc2ql
      @SouravKumar-tc2ql 4 ปีที่แล้ว

      won't I encounter problems? actually, I will be using your code always
      is there class for it?

    • @himanshupednekar
      @himanshupednekar 4 ปีที่แล้ว

      @@SouravKumar-tc2ql no, their is no class for max heap in python.

  • @palakkotwani8351
    @palakkotwani8351 4 ปีที่แล้ว +2

    If this question can be done in O(n) then why are we implementing in O(nlogk) ??

    • @niveshduppalapudi6885
      @niveshduppalapudi6885 3 ปีที่แล้ว

      how?

    • @palakkotwani8351
      @palakkotwani8351 3 ปีที่แล้ว

      @@niveshduppalapudi6885 Using quick sort
      Here you go:www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time/

  • @Sharmaji_ki_ldki
    @Sharmaji_ki_ldki ปีที่แล้ว

    aap bhut acha smjhate ho but the code and the method(java) needed ......

    • @prathampahad9788
      @prathampahad9788 ปีที่แล้ว

      class Solution{
      public static int kthSmallest(int[] arr, int l, int r, int k){
      PriorityQueue pq = new PriorityQueue(Collections.reverseOrder());
      for(int i = 0;ik){
      pq.remove();
      }
      }
      return pq.peek();
      }
      }

    • @prathampahad9788
      @prathampahad9788 ปีที่แล้ว

      Java code @Madhu Sharma

  • @debrajroy1290
    @debrajroy1290 4 ปีที่แล้ว +1

    sir cant it be done using simple array ds?

    • @KeerthiNarayan-c4o
      @KeerthiNarayan-c4o 7 หลายเดือนก่อน

      Yeah that is brute force method
      This explains logic

  • @beardman4152
    @beardman4152 3 ปีที่แล้ว

    bhai java mai ye priority queue wala concept kaam nahi karta. sirf c++ mai chal rha

  • @dhairyashiil
    @dhairyashiil 3 ปีที่แล้ว

    Thank you

  • @datastructure5253
    @datastructure5253 4 ปีที่แล้ว +1

    What if the repeatation is allowed then like array is - > 2 3 3 5 54 232 5 and k = 3 and it gives us output 3 where maximum 3 is 5
    so here your assumption is wrong .

    • @rabindrakumar949
      @rabindrakumar949 4 ปีที่แล้ว

      Each element in heap can be entry of key and value

  • @ankitpandey8967
    @ankitpandey8967 3 ปีที่แล้ว

    Bhaiya agar array main 7 last main hoga to output change nahi hoga

  • @abdullahwaqar3024
    @abdullahwaqar3024 3 ปีที่แล้ว

    what is the time complexity of this program?

  • @yashgupta-rs9ro
    @yashgupta-rs9ro 4 ปีที่แล้ว +2

    Sir array should be sorted because if third element is present in last place in array then it would be popped by algorithm

    • @yashgupta-rs9ro
      @yashgupta-rs9ro 4 ปีที่แล้ว

      Sir please answer me

    • @TheAdityaVerma
      @TheAdityaVerma  4 ปีที่แล้ว

      I dont understand your doubt brother?

    • @yashgupta-rs9ro
      @yashgupta-rs9ro 4 ปีที่แล้ว

      Thank you sir for replying me , I understood the concept completely because of your teaching, thank you sir

    • @SunitaGupta-pz8qk
      @SunitaGupta-pz8qk 4 ปีที่แล้ว

      yes, you are right.

    • @amus2953
      @amus2953 3 ปีที่แล้ว

      sir we need to make sure that element which we are pushing in maxheap should be greatest, but we haven't taken this condition in the code. isn't it???

  • @thesaurabh62057
    @thesaurabh62057 2 ปีที่แล้ว

    thanks sir a lot

  • @ganeshkirankumar6910
    @ganeshkirankumar6910 3 ปีที่แล้ว +3

    PriortyQueue by default is implmenation of MiniHeap, But for this example as we need to use the MaxHep, So in the code above, dont we should use the Compartor.reverseOrder ??
    like PriorityQueue max_heap = new PriorityQueue(Compartor.reverseOrder()) ...

    • @amansinghal4663
      @amansinghal4663 ปีที่แล้ว

      by default, priority queue is max heap in c++, I dont know about other languages

  • @uditkhanna3640
    @uditkhanna3640 4 ปีที่แล้ว

    Priority queue in C++.
    For Java any suitable predefined Class?

    • @suman6327
      @suman6327 4 ปีที่แล้ว +5

      java.util.PriorityQueue // By default its a MinHeap
      For this example :
      int[] input = new int[]{7,10,4,3,20,15};
      int k=3;
      PriorityQueue pq = new PriorityQueue((x,y)->y-x); // Adding a comparator to convert MinHeap to MaxHeap
      for (int i : input) {
      pq.add(i);
      if(pq.size()>k) pq.remove();
      }
      System.out.println("RESULT : ");
      System.out.println(pq.peek());

    • @youryuvv
      @youryuvv 4 ปีที่แล้ว

      @@suman6327 thank you soo much bro..

  • @AB-qu9uv
    @AB-qu9uv 3 ปีที่แล้ว

    This is not working sir. Below given is the code in java. can u pls help me, what went wrong here?
    public static int ksmallest(int arr[],int n,int k)
    {
    int size=0;
    PriorityQueue maxh = new PriorityQueue();
    for(int i=0;ik)
    {
    maxh.poll();
    }
    }
    return maxh.peek();
    }

  • @bat_man1138
    @bat_man1138 3 ปีที่แล้ว

    Acha smghaya bhai

  • @bestsaurabh
    @bestsaurabh 4 ปีที่แล้ว +1

    If I am coding in C, I should use stack to implement the heap?

    • @pavittarkumarazad3259
      @pavittarkumarazad3259 4 ปีที่แล้ว +1

      Usually heap is implemented by a binary tree. You can use BFS in that case to print the elements in sequence.

  • @Music-tp8gg
    @Music-tp8gg 2 ปีที่แล้ว

    Comparison karna padega bro! Jo element pop ho raha hai uska

  • @omprakash007
    @omprakash007 4 ปีที่แล้ว +1

    how to do this question in O(n) ?

    • @geekydanish5990
      @geekydanish5990 4 ปีที่แล้ว

      There is no such sorting algo that provide O(n) don't think so

    • @SachinKumar-nz5bn
      @SachinKumar-nz5bn 4 ปีที่แล้ว +1

      use quick select method to do this in O(n)

  • @Ekam873
    @Ekam873 4 หลายเดือนก่อน +1

    run the code for 1,23,4,5,6 it will not work if yes please explain
    #include
    using namespace std;
    int main()
    {
    priority_queueans;
    int arr[]={1,23,5,9,3};
    int k=2;
    for(int i=0;ik)
    {
    ans.pop();
    }
    ans.push(arr[i]);
    }
    cout

    • @prathamjaiswal3317
      @prathamjaiswal3317 4 หลายเดือนก่อน

      #include
      using namespace std;
      int main() {
      priority_queue ans;
      int arr[] = {1, 23, 5, 9, 3};
      int k = 2;
      for (int i = 0; i < 5; i++) {
      ans.push(arr[i]);
      if (ans.size() > k) {
      ans.pop();
      }
      }
      cout

  • @ankushroy919
    @ankushroy919 4 ปีที่แล้ว

    are bhai heap implement kaise karte hai???????????????????????????????????????

  • @SunitaGupta-pz8qk
    @SunitaGupta-pz8qk 4 ปีที่แล้ว

    How to sort the priority queue?

  • @kamalkumar945
    @kamalkumar945 3 ปีที่แล้ว

    Thanks Bhaiya

  • @rukmanabehera5384
    @rukmanabehera5384 3 ปีที่แล้ว +1

    Bhaiya agar 15 k bad 5 hota ek or number toh output 5 ana chahiye lekin app ne jo bataya iss main nahi ayega output 7 ayega🥲🥲plzz recheak kigiye😶😶

    • @MukeshKumar-ks9zk
      @MukeshKumar-ks9zk 3 ปีที่แล้ว

      explanation is wrong. Eg: arr = 10 , 3 , 4.
      second smallest is needed.
      solution = 4.
      but according to him solution will be = 3 which is wrong

    • @Ritesh_2401
      @Ritesh_2401 3 ปีที่แล้ว

      @@MukeshKumar-ks9zk bro priority queue me element decreasing order me store hote h top to bottom , he forgot to mention it thats why lot of people have same problem

    • @mihirmodi1936
      @mihirmodi1936 ปีที่แล้ว

      Listen 3:49 Carefully!!! 7 Will be on top which will be pop out as size > k and Answer = 5

  • @prasannapm3220
    @prasannapm3220 2 ปีที่แล้ว

    thanks

  • @ramanprasad5857
    @ramanprasad5857 3 ปีที่แล้ว

    how can we implement the code in python

  • @SahilSharma-ug8xk
    @SahilSharma-ug8xk 3 ปีที่แล้ว +2

    Thanks bro I have one query. Please clear it.
    You have made the complexity as nlogk.
    But lets assume normally we have n as a very large value than k. So logk will not make much difference rather klogn will be much more good.
    We can build a complete heap of n elements in O(n) time . And then after that we will call extractMin k times from the heap. Which will cost k logn.
    So overall complexity should be klogn.
    So which out of these two are better solutions. Please comment.

    • @ewananmo2404
      @ewananmo2404 3 ปีที่แล้ว

      Time complexity of building a complete heap is O(nLogn).
      - Logn to find an element's place in the heap
      - n is the number of elements to add to the heap

    • @AbdulRahman-sh8lv
      @AbdulRahman-sh8lv 2 ปีที่แล้ว +1

      @@ewananmo2404 heapify takes O(n)

  • @BTEEELavkushYadav
    @BTEEELavkushYadav 3 ปีที่แล้ว +1

    include
    using namespace std;
    int Kthsmallest(int arr[],int k){
    priority_queue maxh;
    for(int i=0;ik){
    maxh.pop();
    }
    }
    return maxh.top();
    }
    int main(){
    int n,k;
    cin>>k;
    int arr[6]={7,10,4,3,20,15};
    Kthsmallest( arr, k);
    return 0;
    }
    can anyone help me out why this code is not giving output

  • @BlackVoid1998
    @BlackVoid1998 3 ปีที่แล้ว

    Bro time & space complexity of this code ??

  • @SaurabhMelge
    @SaurabhMelge 4 หลายเดือนก่อน

    The code can be optimized by checking the current element is smaller than top of the max heap then in that case only pop and push the element in the heap.
    public static int findKthSmallest(int[] arr, int k) {
    // Max heap to store the k smallest elements
    PriorityQueue maxHeap = new PriorityQueue(Collections.reverseOrder());
    for (int num : arr) {
    // Add the first k elements directly
    if (maxHeap.size() < k) {
    maxHeap.add(num);
    } else {
    // Only add if the current element is smaller than the largest element in the heap
    if (num < maxHeap.peek()) {
    maxHeap.poll(); // Remove the largest element
    maxHeap.add(num); // Add the current element
    }
    }
    }
    // The root of the heap is the k-th smallest element
    return maxHeap.peek();
    }

  • @VikramSingh-hu2hs
    @VikramSingh-hu2hs 3 ปีที่แล้ว +1

    Can't we just use sets

  • @akarshjaiswal1622
    @akarshjaiswal1622 4 ปีที่แล้ว +2

    ❤️❤️❤️

  • @ogorganics3752
    @ogorganics3752 4 ปีที่แล้ว +3

    Backtracking ki vedios kb daloge sir

    • @TheAdityaVerma
      @TheAdityaVerma  4 ปีที่แล้ว +12

      Will upload more video in the month of may !! Till then keep on sharing and help this channel grow + that keeps me motivated to make more videos !! ✌️❤️

  • @anitasharmaist
    @anitasharmaist 4 ปีที่แล้ว

    best !

  • @kuldeepnarayanminj
    @kuldeepnarayanminj 4 ปีที่แล้ว

    lajawaab

  • @niranjankumar-uk8sk
    @niranjankumar-uk8sk 2 ปีที่แล้ว

    bro please upload vedios on linkedlists and bfs and dfs

  • @rishabhbatra3022
    @rishabhbatra3022 3 ปีที่แล้ว

    while using heap ,whats the space complexity?? is it O(n).........if yes then i solved a question on gfg and constraints are Expected Time Complexity: O(n)
    Expected Auxiliary Space: O(1) // but here we have to use O(1) space them how this solution pass?
    Constraints:
    1

  • @ShadowFighterIndia
    @ShadowFighterIndia 6 หลายเดือนก่อน

    ❤❤

  • @louerleseigneur4532
    @louerleseigneur4532 4 ปีที่แล้ว +2

    merci merci

  • @viraj_singh
    @viraj_singh 3 ปีที่แล้ว

    In java we can implement min/max heap in priority queue

  • @rockerboy4184
    @rockerboy4184 3 ปีที่แล้ว

    Roses are red
    Violets are blue
    Your title is in English
    But why aren't you

  • @Sharmaji_ki_ldki
    @Sharmaji_ki_ldki ปีที่แล้ว

    bhaiya java me b code krke bta dia kro kabhi...........

  • @ashishkhar4791
    @ashishkhar4791 3 ปีที่แล้ว

    what if array was 10 4 7 3 5 and k =3
    4 will come at top

    • @pranaychoubey829
      @pranaychoubey829 3 ปีที่แล้ว

      The priority queue implemented in STL sorts the queue in DSC only, so you shouldn't face that problem.

  • @AmanSingh-pq4rf
    @AmanSingh-pq4rf 4 ปีที่แล้ว

    practice.geeksforgeeks.org/problems/kth-smallest-element/0 --- problem link from gfg for those who wanna solve this

  • @JaskaranSingh-hw5jf
    @JaskaranSingh-hw5jf หลายเดือนก่อน

    done

  • @BeardedBong
    @BeardedBong 3 ปีที่แล้ว +4

    ig u missed the point where we need to sort the k elements at the end of program, thats why the complexity becomes NlogK

    • @clashingwithsahib
      @clashingwithsahib 3 ปีที่แล้ว +3

      no need of sorting k elements in the end of program, the top of minheap will give us kth smallest element always.
      the complexity of program is NlogK because to insert a element in a heap it requires log(height of heap) time. so to an insert element to heap it require logk time and we are inserting each element to heap so thats why N comes in time complexity so it become NLogK

  • @darshan.mehta.
    @darshan.mehta. 4 ปีที่แล้ว

    Sir java me bhi bataiye kaise solve kare

  • @sumitraj8143
    @sumitraj8143 4 ปีที่แล้ว

    java solution
    import java.util.Collections;
    import java.util.PriorityQueue;
    import java.util.Scanner;
    public class KthSmallestElement {
    public static int res(int arr[],int k)
    {
    PriorityQueue max=new PriorityQueue(Collections.reverseOrder());
    for(int i=0;ik)
    {
    max.poll();
    }
    }
    return max.peek();
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int arr[]=new int[n];
    for(int i=0;i

  • @krishnakumar-gc6hb
    @krishnakumar-gc6hb 4 ปีที่แล้ว +1

    I think if it is in English . We all would get benefit for non Hindi speakers

  • @codecode-ig8gy
    @codecode-ig8gy 8 หลายเดือนก่อน +1

    class Solution{
    public static int kthSmallest(int[] arr, int l, int r, int k)
    {
    PriorityQueue maxHeap = new PriorityQueue((a, b) -> b - a);
    for(int i:arr){
    maxHeap.add(i);
    if(maxHeap.size()>k){
    maxHeap.poll();
    }
    }
    return maxHeap.peek();
    }
    }

  • @jawwadakhter5261
    @jawwadakhter5261 3 ปีที่แล้ว +10

    Simple python code
    ```import heapq
    l=[7, 10, 4, 3, 20, 15]
    k=3
    heap=[]
    for i in range(0,len(l)):
    heapq.heappush(heap,-l[i])
    if len(heap)>k:
    heapq.heappop(heap)
    print(-heap[0])
    ```

    • @Aryansingh-fk7hy
      @Aryansingh-fk7hy 3 ปีที่แล้ว +1

      is it a compulsion to import the heapq module?

    • @Aryansingh-fk7hy
      @Aryansingh-fk7hy 3 ปีที่แล้ว

      can you tell me,why did you use - in -l[i]?

    • @parinav10
      @parinav10 3 ปีที่แล้ว +2

      @@Aryansingh-fk7hy It is Min Heap by default in the heapq module. Thus, to use it as Max Heap, we take the negative of the values of the list

    • @cp65143
      @cp65143 ปีที่แล้ว

      Thanks

  • @rabindradocument8934
    @rabindradocument8934 2 ปีที่แล้ว

    Apan

  • @unknownname2717
    @unknownname2717 4 ปีที่แล้ว

    PLZ USE FAST INPUT OUTPUT WHILE SUBMISSION THE CODE

  • @pushkarsingh2162
    @pushkarsingh2162 3 หลายเดือนก่อน

    Bilkul kharab video 😢

  • @vedantshinde2277
    @vedantshinde2277 3 ปีที่แล้ว

    GFG Link: practice.geeksforgeeks.org/problems/kth-smallest-element5635/1#

  • @hiteshwarmehla2267
    @hiteshwarmehla2267 ปีที่แล้ว

    public static void main(String[] args) {
    int[] arr = {1,2,4,7,5,6,3};
    int k =3;
    System.out.println(getKthSmallestInteger(arr, k));
    }
    static int getKthSmallestInteger(int[] arr, int k){
    if(arr.length==0){
    return -1;
    }
    //max Heap
    PriorityQueue pQueue = new PriorityQueue(Collections.reverseOrder());
    for(int i=0;i< arr.length;i++){
    pQueue.add(arr[i]);
    if (pQueue.size()>k){
    pQueue.poll();
    }
    }
    return pQueue.peek();
    }

  • @sakshid1724
    @sakshid1724 2 ปีที่แล้ว

    Works - practice.geeksforgeeks.org/problems/kth-smallest-element/0
    int kthSmallest(int arr[], int l, int r, int k) {
    //code here
    priority_queuemax_heap;
    for(int i = l; i k){
    max_heap.pop();
    }
    }

    return max_heap.top();
    }