2026 February 21 Problems

29 views
Skip to first unread message

daryl...@gmail.com

unread,
Feb 21, 2026, 12:36:40 PMFeb 21
to leetcode-meetup
Feel free to work on any of the problems you want; we'll have people present their solutions at 11:30.

Please post your solutions to this thread so others can use this as a reference.

We had a lot of discussion on last week's medium problem, so it's been carried over to this week as well.

933. Number of Recent Calls Easy 78.1%

2467. Most Profitable Path in a Tree Medium 67.3%

3508. Implement Router Medium 39.2%

We're going to use the same Google meet link as the last few times: https://meet.google.com/xnn-kifj-jnx?pli=1



Anuj Patnaik

unread,
Feb 21, 2026, 1:39:16 PMFeb 21
to leetcode-meetup
class Router:
def __init__(self, memoryLimit: int):
self.memlim = memoryLimit
self.queue = []
self.set_of_packets = set()
self.dest_to_time = defaultdict(list)
self.start = 0
self.dest_start = defaultdict(int)
def addPacket(self, source: int, destination: int, timestamp: int) -> bool:
packet = (source, destination, timestamp)
if packet in self.set_of_packets:
return False
if len(self.queue) - self.start == self.memlim:
oldest_packet = self.queue[self.start]
oldest_dest = oldest_packet[1]
self.start += 1
self.dest_start[oldest_dest] += 1
self.set_of_packets.remove(tuple(oldest_packet))
self.queue.append(list(packet))
self.set_of_packets.add(packet)
self.dest_to_time[destination].append(timestamp)
return True

def forwardPacket(self) -> List[int]:
if self.start == len(self.queue):
return []
first_packet = self.queue[self.start]
self.start += 1
destination = first_packet[1]
self.dest_start[destination] += 1
self.set_of_packets.remove(tuple(first_packet))
return first_packet
def getCount(self, destination: int, startTime: int, endTime: int) -> int:
count = 0
arr = self.dest_to_time[destination]
start_index = self.dest_start[destination]

left_start = start_index
right_start = len(arr)

while left_start < right_start:
mid_start = (left_start + right_start) // 2
if arr[mid_start] < startTime:
left_start = mid_start + 1
else:
right_start = mid_start
startTimeBound = left_start

left_end = start_index
right_end = len(arr)
while left_end < right_end:
mid_end = (left_end + right_end) // 2
if arr[mid_end] <= endTime:
left_end = mid_end + 1
else:
right_end = mid_end
endTimeBound = left_end
return endTimeBound - startTimeBound


# Your Router object will be instantiated and called as such:
# obj = Router(memoryLimit)
# param_1 = obj.addPacket(source,destination,timestamp)
# param_2 = obj.forwardPacket()
# param_3 = obj.getCount(destination,startTime,endTime)

Allen S.

unread,
Feb 21, 2026, 1:43:30 PMFeb 21
to leetcode-meetup
type RecentCounter struct {
q []int
}


func Constructor() RecentCounter {
return RecentCounter{
q: []int{},
}
}


func (this *RecentCounter) Ping(t int) int {
this.q = append(this.q, t)

for this.q[0] < t - 3000 {
this.q = this.q[1:]
}
return len(this.q)
}

Anuj Patnaik

unread,
Feb 21, 2026, 2:06:26 PMFeb 21
to leetcode-meetup
class RecentCounter:

def __init__(self):
self.queue = []
def ping(self, t: int) -> int:
self.queue.append(t)
while len(self.queue) > 0 and self.queue[0] < t - 3000:
self.queue.pop(0)
return len(self.queue)

Rag Mur

unread,
Feb 21, 2026, 2:17:37 PMFeb 21
to leetcode-meetup
933. Number of Recent Calls Easy 78.1%

from collections import deque

class RecentCounter:
def __init__(self):
self.TIME_WINDOW_SIZE = 3000 # milliseconds
# stores t in the order it arrives
# Assumption: t is strictly increasing
# if the t not strictly increasing we have to use monotonic queue
self.queue = deque()

def ping(self, t: int) -> int:
self.queue.append(t)
while self.queue and self.queue[0] < max(0, t - self.TIME_WINDOW_SIZE):
self.queue.popleft()
return len(self.queue)

2467. Most Profitable Path in a Tree Medium 67.3%

from collections import defaultdict
class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
INF = float('inf')

# this stuct maintains the distance from B to A's staring node.
# if a node is not in the path, the distance will the INF.
# Example: [inf, inf, inf, inf, inf] --> [2, 1, inf, 0, inf]
# where nodes 0, 1, and 3 in the path

path_len_from_b_to_a = [INF]*len(amount)

graph = defaultdict(list)
for i, j in edges:
graph[i].append(j)
graph[j].append(i)

def calculate_path(prev_node, node, distance):
if node == 0:
path_len_from_b_to_a[node] = distance
return True
for neighbor in graph[node]:
if neighbor != prev_node:
if calculate_path(node, neighbor, distance+1):
path_len_from_b_to_a[node] = distance
return True
return False

# print(path_len_from_b_to_a)
calculate_path(-1, bob, 0)
# print(path_len_from_b_to_a)

self.max_profit = -float('inf')

# One of the path in traversing all neighbours is same path
# through which A arrived at the current node. This path should not be visited again
# Since this path is already evaluated.
# prev node is passed here to prevent this revisiting.
def find_alice_max(curr, prev, distance, current_income):
# Calculate Alice's share at this node
if distance < path_len_from_b_to_a[curr]:
# this node lies either less than half distance of path_len_from_b_to_a in path from A to B
# OR
# this node is not in path from A to B (INF)
current_income += amount[curr]
elif distance == path_len_from_b_to_a[curr]:
current_income += amount[curr] // 2
# Check if it's a leaf node (not root)
# this a edge case if the root node is a leaf, we should still perform recursion.
if len(graph[curr]) == 1 and curr != 0:
self.max_profit = max(self.max_profit, current_income)
return

for neighbor in graph[curr]:
if neighbor != prev:
find_alice_max(neighbor, curr, distance + 1, current_income)

find_alice_max(0, -1, 0, 0)
return self.max_profit


3508. Implement Router Medium 39.2%

from collections import deque
from sortedcontainers import SortedList

class Router:
def __init__(self, memoryLimit: int):
# a O(1) lookup struct to check is the a packet is alreary in dict
# Key is a set(src, dest, timestamp)
self.packets = set()

# fifo queue to forward the first entered packet
self.queue = deque()
# stores all the packets to a dest ordered by times
# key : (dest)
# val: sorted [timestamps]
self.dest_packet_index = defaultdict(SortedList)

# max packets that can be stored.
# If adding a new packet would exceed this limit, the oldest packet must be removed to free up space.
self.memoryLimit = memoryLimit

def _delete(self, key):
self.packets.remove(key)
self.dest_packet_index[key[1]].pop(0)

def addPacket(self, source: int, destination: int, timestamp: int) -> bool:
new_packet_key = (source, destination, timestamp)
if new_packet_key in self.packets:
# no op. the packlet already exist
return False
if len(self.queue) >= self.memoryLimit:
self._delete(self.queue.popleft())
self.packets.add(new_packet_key)
self.dest_packet_index[new_packet_key[1]].add(timestamp)
self.queue.append(new_packet_key)
return True

def forwardPacket(self) -> List[int]:
packet = []
if self.queue:
oldest_packect_key = self.queue.popleft()
self._delete(oldest_packect_key)
packet = list(oldest_packect_key)
return packet

def getCount(self, destination: int, startTime: int, endTime: int) -> int:
if destination not in self.dest_packet_index:
return 0
sl = self.dest_packet_index[destination]
low_idx = sl.bisect_left(startTime)
high_idx = sl.bisect_right(endTime)
return high_idx - low_idx


On Saturday, February 21, 2026 at 9:36:40 AM UTC-8 daryl...@gmail.com wrote:

Jagrut

unread,
Feb 21, 2026, 2:29:07 PMFeb 21
to leetcode-meetup
3508. Implement Router Medium 39.2%

from sortedcontainers import SortedList
from collections import deque

class Router:

def __init__(self, memoryLimit: int):
self.capacity = memoryLimit
self.seen = set()
self.q = deque()
self.destTimes = {}

def addPacket(self, source: int, destination: int, timestamp: int) -> bool:
packet = (source, destination, timestamp)
if packet in self.seen:
return False
if len(self.q) == self.capacity:
self.forwardPacket()
# Now, we have space and have not seen this
self.q.append(packet)
if destination not in self.destTimes:
self.destTimes[destination] = SortedList()
self.destTimes[destination].add(timestamp)
self.seen.add(packet)
return True

def forwardPacket(self) -> List[int]:
packet = None
if self.q:
packet = self.q.popleft()
destination = packet[1]
timestamp = packet[2]
self.seen.remove(packet)
self.destTimes[destination].remove(timestamp)
return list(packet) if packet else []

def getCount(self, destination: int, startTime: int, endTime: int) -> int:
if destination not in self.destTimes:
return 0
# Binary search
timestamps = self.destTimes[destination]
lower_ts_idx = timestamps.bisect_left(startTime)
upper_ts_idx = timestamps.bisect_right(endTime)
return upper_ts_idx - lower_ts_idx


# Your Router object will be instantiated and called as such:
# obj = Router(memoryLimit)
# param_1 = obj.addPacket(source,destination,timestamp)
# param_2 = obj.forwardPacket()
# param_3 = obj.getCount(destination,startTime,endTime)
On Saturday, February 21, 2026 at 9:36:40 AM UTC-8 daryl...@gmail.com wrote:

Jagrut

unread,
Feb 21, 2026, 3:44:38 PMFeb 21
to leetcode-meetup
933. Number of Recent Calls Easy 78.1%

class RecentCounter:

def __init__(self):
self.q = []
self.left_boundary_idx = 0
self.WINDOW_SIZE: int = 3000

def ping(self, t: int) -> int:
self.q.append(t)
left_idx = self.search_least_higher_or_equal(self.q, self.left_boundary_idx, t - self.WINDOW_SIZE)
self.left_boundary_idx = left_idx
return len(self.q) - left_idx

def search_least_higher_or_equal(self, a: list[int], low: int, v: int) -> int:
high = len(a) - 1
res = -1
while (low <= high):
mid = low + (high - low) // 2
if a[mid] >= v:
res = mid
high = mid - 1
else:
low = mid + 1
return len(a) if res == -1 else res

On Saturday, February 21, 2026 at 9:36:40 AM UTC-8 daryl...@gmail.com wrote:

vinay

unread,
Feb 21, 2026, 6:25:24 PMFeb 21
to leetcod...@googlegroups.com
2467. Most Profitable Path in a Tree Medium 67.3%
 
Let bob play first and mark timestamps on each node along his path to 0.

 Alice then traverses from 0 to all leaves, comparing her arrival time to Bob's timestamps to determine if she gets full cost, half, or zero.  

Time, Space O(N)

class Solution {
    int profit = Integer.MIN_VALUE;

    public int mostProfitablePath(int[][] edges, int bob, int[] amount) {
        Map<Integer, List<Integer>> adjs = new HashMap<>();
        int[] timestamps = new int[amount.length];
        boolean[] visited = new boolean[amount.length];
       
        Arrays.fill(timestamps, -1);
       
        for(int i = 0; i < edges.length; i++){
            int from = edges[i][0];
            int to = edges[i][1];
            adjs.computeIfAbsent(from, k -> new ArrayList<>()).add(to);
            adjs.computeIfAbsent(to, k -> new ArrayList<>()).add(from);
        }
       
        //lets bob play and timestamp each node first
        bobDFS(adjs, bob, timestamps, visited, 0);

        Arrays.fill(visited, false);
       
        //calculate node 0's cost
        int startCost = amount[0];
        if(timestamps[0] == 0) {
            startCost /= 2;
        }
       
        //let alice traverse from 0 to all leaves, collect max money
        aliceDFS(adjs, timestamps, visited, amount, 0, 0, startCost);

        return profit;
    }

    public boolean bobDFS(Map<Integer, List<Integer>> adjs, int node, int[] timestamps, boolean[] visited, int time){
        visited[node] = true;
       
        if(node == 0){
            timestamps[node] = time;
            return true;
        }

        for(int neighbor : adjs.getOrDefault(node, new ArrayList<>())){
            if(!visited[neighbor] && bobDFS(adjs, neighbor, timestamps, visited, time+1)){
                timestamps[node] = time;
                return true;
            }
        }

        return false;
    }

    public void aliceDFS(Map<Integer, List<Integer>> adjs, int[] timestamps, boolean[] visited, int[] amount, int node, int time, int sum){
        visited[node] = true;

        //we hit the leaf
        if(node != 0 && adjs.getOrDefault(node, new ArrayList<>()).size() == 1){
            profit = Math.max(profit, sum );
            return;
        }

        for(int neighbor : adjs.getOrDefault(node, new ArrayList<>())){
            int nodeCost = amount[neighbor];
            //follow the conditions about gates
            if(timestamps[neighbor] != -1) {
                if(timestamps[neighbor] == time+1){
                    nodeCost /= 2;
                } else if(timestamps[neighbor] < time+1) {
                    nodeCost = 0;
                }
            }

            if(!visited[neighbor]){
                aliceDFS(adjs, timestamps, visited, amount, neighbor, time+1, sum + nodeCost);
            }
        }
    }
}

--
whatspp group: http://whatsapp.techbayarea.us/
---
You received this message because you are subscribed to the Google Groups "leetcode-meetup" group.
To unsubscribe from this group and stop receiving emails from it, send an email to leetcode-meet...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/leetcode-meetup/b8203935-bace-4b5d-89bc-73e39526f463n%40googlegroups.com.

Jagrut

unread,
Feb 22, 2026, 2:43:03 AMFeb 22
to leetcode-meetup
class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
"""
Step 1: Make the tree as an adjacency list (graphical rep)
"""
g = defaultdict(list)
for edge in edges:
from_node = edge[0]
to_node = edge[1]
g[from_node].append(to_node)
g[to_node].append(from_node)
# print(tree)

"""
Step 2: Find the path that Bob will take to node 0
DFS
"""
# node_visited_on_route_path -> time_of_visit
bob_journey = defaultdict(int)

def dfs_bob(current, previous, time) -> bool:
if (current == 0):
# Bob has reached 0
bob_journey[current] = time
return True

for neighbor in g[current]:
# make sure we don't go back to where we came from
if neighbor != previous:
route_to_0_found = dfs_bob(neighbor, current, time + 1)
if route_to_0_found:
# current node is on path to 0
bob_journey[current] = time
# no need to explore other neighbors
return True
# No neighbor of current leads to 0
return False

# Kick-off DFS for Bob
dfs_bob(bob, -1, 0)

"""
Step 3: Find the paths that Alice will take to reach leaf nodes
BFS
"""
@dataclass
class State:
node: int
time: int
previous: int
total_profit: int

q = deque()
# Alice starts from node 0
q.append(State(0, 0, -1, amount[0]))
result = float("-inf")
while q:
state: State = q.popleft()
for neighbor in g[state.node]:
# Don't go back to where you came from
if (neighbor != state.previous):
# Assume you got here in isolation, we'll worry about Bob in a bit
neighbor_profit = amount[neighbor]
# Time to reach neighbor is 1 more than it took to get here
alice_neighbor_time = state.time + 1
# Did Bob ever get here? If so, adjust the profit
if neighbor in bob_journey:
bob_neighbor_time = bob_journey.get(neighbor)
# Alice and Bob got here at same time, split profits
if alice_neighbor_time == bob_neighbor_time:
neighbor_profit = amount[neighbor] // 2
# Alice was late, Bob came earlier, Alice gets 0 profit
elif alice_neighbor_time > bob_neighbor_time:
neighbor_profit = 0

# New state in queue. Note that total profit is updated.
q.append(State(neighbor,
alice_neighbor_time,
state.node,
state.total_profit + neighbor_profit)
)

# Keep track of best leaf
# If neighbor is leaf, let's record the result
if len(g[neighbor]) == 1:
result = max(result, state.total_profit + neighbor_profit)
return result


On Saturday, February 21, 2026 at 9:36:40 AM UTC-8 daryl...@gmail.com wrote:
Reply all
Reply to author
Forward
0 new messages