Skip to content

Commit

Permalink
Create solution.java
Browse files Browse the repository at this point in the history
  • Loading branch information
RiH-137 authored Oct 12, 2024
1 parent 61397f1 commit 824abd4
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions The Number of the Smallest Unoccupied Chair/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
class Item {
int friend;
int chair = -1;
int startTime;
int endTime;

public Item(int friend, int startTime, int endTime) {
this.friend = friend;
this.startTime = startTime;
this.endTime = endTime;
}

public void setChair(int chair) {
this.chair = chair;
}
}

class Solution {
public int smallestChair(int[][] times, int targetFriend) {
Item[] arrival = new Item[times.length];

PriorityQueue<Integer> available = new PriorityQueue<>();
PriorityQueue<Item> assigned = new PriorityQueue<>((a, b) -> a.endTime - b.endTime);

for (int i = 0; i < times.length; i++) {
arrival[i] = new Item(i, times[i][0], times[i][1]);
available.add(i);
}

// here i am Sorting friends by their arrival times
Arrays.sort(arrival, (a, b) -> a.startTime - b.startTime);

for (int i = 0; i < arrival.length; i++) {
Item item = arrival[i];

//here i am Freeing up chairs for people who have left by this time
while (!assigned.isEmpty() && assigned.peek().endTime <= item.startTime) {
available.add(assigned.poll().chair);
}

// now Assign the smallest available chair to the current friend
item.setChair(available.poll());
assigned.add(item);

// If this is the target friend, return their chair number
if (item.friend == targetFriend) {
return item.chair;
}
}

return -1;
}
}

0 comments on commit 824abd4

Please sign in to comment.