Heap
Heap
The number of soldiers in row i is less than the number of soldiers in row j.
Both rows have the same number of soldiers and i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
Example 1:
Input: mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
Simmilar Q : https://leetcode.com/problems/kth-largest-element-in-a-stream/
https://leetcode.com/problems/k-closest-points-to-origin/
Sol :
Whenever we get a question where we are asked to keep *K* or Kth of something we will use min or
max heap and pop the element when the length of heap goes greater than K
x = []
ans = []
for i in range(len(y)):
cc = 0
for j in range(len(y[i])):
cc+=y[i][j]
heapq.heappush(x,[-cc,-i])
if(len(x)>k):
heapq.heappop(x)
for i in range(len(x)):
ans.append(abs(heapq.heappop(x)[1]))
return ans[::-1]
Return the answer sorted by the frequency from highest to lowest. Sort the words with the
same frequency by their lexicographical order.
Example 1:
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with
the number of occurrence being 4, 3, 2 and 1 respectively.
Sol : We need to keep elements in heap so that the freq is sorted in greatest to lowest and string by
lower to higher
But heap do all element by either max or either min so we have to edit how the heap sorts the data
class Node:
def __init__(self, freq, word):
self.word = word
self.freq = freq
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
done = {}
d = {}
for i in words:
if(i not in d):
d[i]=1
else:
d[i]+=1
x = []
for i in words:
if(i not in done):
ret = Node(d[i],i)
heapq.heappush(x,ret)
if(len(x)>k):
heapq.heappop(x)
done[i]=1
ans = []
for i in range (len(x)):
ans.append(heapq.heappop(x).word)
ans.reverse()
return(ans)
373. Find K Pairs with Smallest Sums
Medium
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u, v) which consists of one element from the first array and one element from
the second array.
Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
Example 1:
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],
[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Output: [[1,1],[1,1]]
Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],
[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Output: [[1,3],[2,3]]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
Sol :
Dijakstra
x = [[a[0]+b[0],[0,0]]]
visited = {}
visited[(0,0)]=1
ans = []
while(len(ans)<k and len(x)<=k and len(x)):
ss = heapq.heappop(x)[1]
ans.append([a[ss[0]],b[ss[1]]])
try:
if((ss[0]+1,ss[1]) not in visited):
val = a[ss[0]+1]+b[ss[1]]
heapq.heappush(x,[val,[ss[0]+1,ss[1]]])
visited[(ss[0]+1,ss[1])]=1
except:
do = "nothing"
try:
if((ss[0],ss[1]+1) not in visited):
val = a[ss[0]]+b[ss[1]+1]
heapq.heappush(x,[val,[ss[0],ss[1]+1]])
visited[(ss[0],ss[1]+1)]=1
except:
do = "nothing"
return ans
621. Task Scheduler { DO AGAIN }
Medium
58181089Add to ListShare
Given a characters array tasks, representing the tasks a CPU needs to do, where each letter
represents a different task. Tasks could be done in any order. Each task is done in one unit of
time. For each unit of time, the CPU could complete either one task or just be idle.
Return the least number of units of times that the CPU will take to finish all the given tasks.
Example 1:
Output: 8
Explanation:
https://leetcode.com/problems/task-scheduler/
x = []
for i in d:
x.append([-d[i],i,-1])
heapq.heapify(x)
tot = len(t)
q = deque([])
kk = 1
while(len(x)>0 or len(q)>0):
while(len(q) and q[0][2]<=kk):
heapq.heappush(x, q[0])
q.popleft()
if(len(x)>0):
ss = heapq.heappop(x)
kk+=1
ss[0]+=1
if(ss[0]<0):
q.append([ss[0],ss[1],kk+k])
else:
if(len(q)>0):
heapq.heappush(x, q[0])
tot+= q[0][2]-kk
kk = q[0][2]
q.popleft()
return(tot)
1642. Furthest Building You Can Reach
Medium
130544Add to ListShare
You are given an integer array heights representing the heights of buildings, some bricks, and
some ladders.
You start your journey from building 0 and move to the next building by possibly using bricks or
ladders.
If the current building's height is greater than or equal to the next building's height, you
do not need a ladder or bricks.
If the current building's height is less than the next building's height, you can either
use one ladder or (h[i+1] - h[i]) bricks.
Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks
optimally.
Example 1:
Output: 4
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2
< 7.
- Go to building 4 using your only ladder. You must use either bricks or ladders
because 6 < 9.
It is impossible to go beyond building 4 because you do not have any more bricks
or ladders.
Sol :
We will traverse the array and will keep pushing the diff(curr-prev) in the max heap and will keep
sum of diff pushed into the heap till now
when this sum gets over the bricks we have we will check if we have a ladder if we don’t have we
will return until this index
Else we will use the ladder for the maximum difference and deduct the diff from sum
We are doing this because when we exceed the total bricks we have we cannot go further anyhow
so we will use ladder for this
tot = 0
x = []
curr = a[0]
for i in range(1,len(a)):
if(a[i]>curr):
heapq.heappush(x,-(a[i]-curr))
tot+=(a[i]-curr)
curr = a[i]
if(tot>b):
if(l>0):
s = heapq.heappop(x)
l-=1
tot-= abs(s)
else:
return i-1
else:
curr = a[i]
return len(a)-1
1705. Maximum Number of Eaten Apples
Medium
410139Add to ListShare
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the
tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the
apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any
apples, which are denoted by apples[i] == 0 and days[i] == 0.
You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep
eating after the first n days.
Given two integer arrays days and apples of length n, return the maximum number of apples
you can eat.
Example 1:
Output: 7
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day,
the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.
Sol :
We will traverse the array add the expiry date and no of apples to min heap pop out the element
with the minimum expiry date check if it is expired or not eat 1 apple from it and push back it to the
heap.
tot = 0
x = []
for i in range(len(a)):
s = heapq.heappop(x)
if(s[0]>=i):
s[1]-=1
tot+=1
if(s[1]>0 and s[0]>i):
heapq.heappush(x,s)
i = len(a)
if(len(x)>0):
while(len(x)>0):
while(len(x)>0 and x[0][0]<i):
heapq.heappop(x)
if(len(x)>0):
s = heapq.heappop(x)
if(s[0]>=i):
s[1]-=1
tot+=1
if(s[1]>0 and s[0]>i):
heapq.heappush(x,s)
i+=1
return(tot)
1942. The Number of the Smallest Unoccupied Chair
Medium
There is a party where n friends numbered from 0 to n - 1 are attending. There is
an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend
arrives at the party, they sit on the unoccupied chair with the smallest number.
For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair
number 2.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If
another friend arrives at that same moment, they can sit in that chair.
You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi],
indicating the arrival and leaving times of the ith friend respectively, and an
integer targetFriend. All arrival times are distinct.
Return the chair number that the friend numbered targetFriend will sit on.
Example 1:
Output: 1
Sol :
We will use 2 min heaps 1 will keep the unoccupied chairs and another will keep
the occupied seats and who is sitting on it
We will traverse check which minimum index chair is available assign that chair to current friend and
push it to the occupied heap , we will also add check if there is any friend who left and add those
chairs back to available chair heap.
t = tm.copy()
t.sort(key= lambda x:(x[0],x[1]))
x = [i for i in range(len(t)+1)]
heapq.heapify(x)
y = []
for i in range(len(t)):
while(len(y)>0 and y[0][0]<= t[i][0]):
ss = heapq.heappop(y)
heapq.heappush(x,ss[1])
minn = heapq.heappop(x)
heapq.heappush(y,[t[i][1],minn])
if(t[i]==tm[tf]):
return minn