Problem solution · Java

Implement Router

Implement Router: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
106 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Implement Router, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 106 lines of Java from the credited upstream file 3508.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue, cached states.
  • 2 loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeImplement Router · JavaJava
Use this to learn the idea, then write your own version.
class Packet implements Comparable<Packet> {  public int source;  public int destination;  public int timestamp;   public Packet(int source, int destination, int timestamp) {    this.source = source;    this.destination = destination;    this.timestamp = timestamp;  }   @Override  public int compareTo(Packet other) {    if (source != other.source)      return Integer.compare(source, other.source);    if (destination != other.destination)      return Integer.compare(destination, other.destination);    return Integer.compare(timestamp, other.timestamp);  }   @Override  public boolean equals(Object o) {    if (this == o)      return true;    if (o == null || getClass() != o.getClass())      return false;    Packet packet = (Packet) o;    return source == packet.source && destination == packet.destination &&        timestamp == packet.timestamp;  }   @Override  public int hashCode() {    return Objects.hash(source, destination, timestamp);  }} class Router {  public Router(int memoryLimit) {    this.memoryLimit = memoryLimit;  }   public boolean addPacket(int source, int destination, int timestamp) {    Packet packet = new Packet(source, destination, timestamp);    if (uniquePackets.contains(packet))      return false;    if (packetQueue.size() == memoryLimit)      forwardPacket();    packetQueue.add(packet);    uniquePackets.add(packet);    destinationTimestamps.computeIfAbsent(destination, k -> new ArrayList<>()).add(timestamp);    return true;  }   public List<Integer> forwardPacket() {    if (packetQueue.isEmpty())      return Collections.emptyList();    Packet nextPacket = packetQueue.poll();    uniquePackets.remove(nextPacket);    processedPacketIndex.merge(nextPacket.destination, 1, Integer::sum);    return Arrays.asList(nextPacket.source, nextPacket.destination, nextPacket.timestamp);  }   public int getCount(int destination, int startTime, int endTime) {    if (!destinationTimestamps.containsKey(destination))      return 0;    List<Integer> timestamps = destinationTimestamps.get(destination);    final int startIndex = processedPacketIndex.getOrDefault(destination, 0);    final int lowerBoundIndex = firstGreaterEqual(timestamps, startIndex, startTime);    final int upperBoundIndex = firstGreater(timestamps, lowerBoundIndex, endTime);    return upperBoundIndex - lowerBoundIndex;  }   private final int memoryLimit;  private final TreeSet<Packet> uniquePackets = new TreeSet<>();  private final Queue<Packet> packetQueue = new LinkedList<>();  private final Map<Integer, List<Integer>> destinationTimestamps = new HashMap<>();  private final Map<Integer, Integer> processedPacketIndex = new HashMap<>();   private int firstGreaterEqual(List<Integer> timestamps, int startIndex, int startTime) {    int l = startIndex;    int r = timestamps.size();    while (l < r) {      final int m = (l + r) / 2;      if (timestamps.get(m) >= startTime)        r = m;      else        l = m + 1;    }    return l;  }   private int firstGreater(List<Integer> timestamps, int startIndex, int endTime) {    int l = startIndex;    int r = timestamps.size();    while (l < r) {      final int m = (l + r) / 2;      if (timestamps.get(m) > endTime)        r = m;      else        l = m + 1;    }    return l;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗