Problem solution · Java

Count Mentions Per User

Count Mentions Per User: 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
56 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 Count Mentions Per User, 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

  • 56 lines of Java from the credited upstream file 3433.java.
  • The implementation visibly relies on sequence storage, work queue.
  • 6 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 codeCount Mentions Per User · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int[] countMentions(int numberOfUsers, List<List<String>> events) {    record OfflineUser(int returnTimestamp, int userId) {}    int[] ans = new int[numberOfUsers];    boolean[] online = new boolean[numberOfUsers];    Arrays.fill(online, true);    // min-heap to track users that are offline    Queue<OfflineUser> offlineQueue =        new PriorityQueue<>(Comparator.comparingInt(OfflineUser::returnTimestamp));    int allMentionsCount = 0;     events.sort(        Comparator.comparingInt((List<String> event) -> Integer.parseInt(event.get(1)))            .thenComparing((List<String> event) -> event.get(0), Comparator.reverseOrder()));     for (List<String> event : events) {      final String eventType = event.get(0);      final int timestamp = Integer.parseInt(event.get(1));      // Bring users back online if their offline period has ended.      while (!offlineQueue.isEmpty() && offlineQueue.peek().returnTimestamp <= timestamp)        online[offlineQueue.poll().userId] = true;      if (eventType.equals("MESSAGE")) {        String mentionsString = event.get(2);        if (mentionsString.equals("ALL")) {          ++allMentionsCount;        } else if (mentionsString.equals("HERE")) {          for (int userId = 0; userId < numberOfUsers; ++userId)            if (online[userId])              ++ans[userId];        } else {          for (final int userId : getUserIds(mentionsString))            ++ans[userId];        }      } else if (eventType.equals("OFFLINE")) {        final int userId = Integer.parseInt(event.get(2));        online[userId] = false;        // Add to queue to bring back online after 60 units        offlineQueue.offer(new OfflineUser(timestamp + 60, userId));      }    }     // Add the "ALL" mentions to all users.    for (int userId = 0; userId < numberOfUsers; ++userId)      ans[userId] += allMentionsCount;     return ans;  }   private List<Integer> getUserIds(final String s) {    List<Integer> integers = new ArrayList<>();    for (String part : s.split(" "))      integers.add(Integer.parseInt(part.substring(2)));    return integers;  }} 

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 ↗