codes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

ASSIGNMENT – 2

1) K – LARGEST ELEMENT IN AN ARRAY

import heapq

class Solution:
def findKthLargest(self, nums, k):
min_heap = []
for num in nums:
heapq.heappush(min_heap, num)
if len(min_heap) > k:
heapq.heappop(min_heap)

return min_heap[0]
nums1 = [3, 2, 1, 5, 6, 4]
k1 = 2
print(Solution().findKthLargest(nums1, k1))

nums2 = [3, 2, 3, 1, 2, 4, 5, 5, 6]
k2 = 4
print(Solution().findKthLargest(nums2, k2))

OUTPUT:
2)MERGE K SORTED LISTS

import heapq

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def to_list(self):
result = []
current = self
while current:
result.append(current.val)
current = current.next
return result

class Solution:
def mergeKLists(self, lists):
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))

dummy = ListNode(0)
current = dummy

while heap:
val, i, node = heapq.heappop(heap)
current.next = node
current = current.next
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))

return dummy.next

def create_linked_list(arr):
dummy = ListNode(0)
current = dummy
for val in arr:
current.next = ListNode(val)
current = current.next
return dummy.next
lists = [create_linked_list([1, 4, 5]), create_linked_list([1, 3, 4]), create_linked_list([2, 6])]
result = Solution().mergeKLists(lists)
print(result.to_list()) # Output: [1, 1, 2, 3, 4, 4, 5, 6]

OUTPUT:
2) DESIGN CIRCULAR DEQUE

class MyCircularDeque:
def __init__(self, k: int):
self.k = k
self.deque = [0] * k
self.front = 0
self.rear = 0
self.count = 0

def insertFront(self, value: int) -> bool:


if self.isFull():
return False
self.front = (self.front - 1) % self.k
self.deque[self.front] = value
self.count += 1
return True

def insertLast(self, value: int) -> bool:


if self.isFull():
return False
self.deque[self.rear] = value
self.rear = (self.rear + 1) % self.k
self.count += 1
return True

def deleteFront(self) -> bool:


if self.isEmpty():
return False
self.front = (self.front + 1) % self.k
self.count -= 1
return True

def deleteLast(self) -> bool:


if self.isEmpty():
return False
self.rear = (self.rear - 1) % self.k
self.count -= 1
return True

def getFront(self) -> int:


if self.isEmpty():
return -1
return self.deque[self.front]
def getRear(self) -> int:
if self.isEmpty():
return -1
return self.deque[(self.rear - 1) % self.k]

def isEmpty(self) -> bool:


return self.count == 0

def isFull(self) -> bool:


return self.count == self.k

OUTPUT:

You might also like