diff --git a/Heap/P03_FindKthLargestElementInArray.py b/Heap/P03_FindKthLargestElementInArray.py new file mode 100644 index 0000000..12738ac --- /dev/null +++ b/Heap/P03_FindKthLargestElementInArray.py @@ -0,0 +1,30 @@ +import Heap + +def findKthLargestElement(nums:list,k:int): + ''' + The problem here is to find the Kth Largest Element from the array. + to solve this we could've used sort and given the answer but it would've cost us O(N*logN) where N is the number of elements in the array + + to even optimize that solution we can use heaps. + the idea here is: + 1. create a min-heap with adding all the values as negative to it + 2. deleting till second last step + 3. returning the element at the last step as the answer + + T - O(N +K*log(N)) where K is the position of Kth largest element and N is the number of elements in the array + + ''' + h=Heap.BinaryHeap() + [h.insert(-num) for num in nums] + [h.delete() for _ in range(k-1)] + + return -h.delete() + + +if __name__ == '__main__': + + nums=[2,3,5,6,4] + k=2 + kthLargestElement = findKthLargestElement(nums,k) + + print("the Kth("+str(k)+") largest element is",kthLargestElement) \ No newline at end of file diff --git a/Linked Lists/P03_FindingMidOfLinkedList.py b/Linked Lists/P03_FindingMidOfLinkedList.py new file mode 100644 index 0000000..faad4d6 --- /dev/null +++ b/Linked Lists/P03_FindingMidOfLinkedList.py @@ -0,0 +1,39 @@ +# Author: VARNIT SHARMA (LunaticProgrammer) + +import SinglyLinkedList + +def findMid(myLinkedList): + ''' + The approch is simple: + 1. creating a fast pointer that is moving and skipping one element of the linked-list + 2. creating a slow pointer that goes through every next element in the linked-list + 3. when the fast pointer has reached the end the slower one is supposed to be at mid + 4. return the element pointed by slow pointer + + Time-O(logN) where N is the number of elements in linked-list + + ''' + if not myLinkedList or not myLinkedList.head.next: return myLinkedList.head + + slow = myLinkedList.head + fast = myLinkedList.head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + return slow + + +if __name__ == '__main__': + myLinkedList = SinglyLinkedList.LinkedList() + for i in range(10, 0, -1): + myLinkedList.insertAtStart(i) + print("LinkedList",end=" ") + myLinkedList.printLinkedList() + print() + midleElement = findMid(myLinkedList) + print("The middle element of the LinkedList is",midleElement.data) + + # OUTPUT: + # The middle element of the LinkedList is 6