Analyzing Group Lifetimes in a Social Networking App Using Java

Introduction

Welcome to our new coding practice lesson! We have an interesting problem in this unit that centers around data from a social networking app. The challenge involves processing logs from this app and extracting useful information from them. This task will leverage your skills in string manipulation, working with timestamps, and task subdivision. Let's get started!

Task Statement

Imagine a social networking application that allows users to form groups. Each group has a unique ID ranging from 1 to n, where n is the total number of groups. Interestingly, the app keeps track of when a group is created and deleted, logging all these actions in a string.

The task before us is to create a Java method named analyzeLogs. This method will take as input a string of logs and output a List<String> representing the groups with the longest lifetime. Each string in the list contains two items separated by a space: the group ID and the group's lifetime. By 'lifetime,' we mean the duration from when the group was created until its deletion. If a group has been created and deleted multiple times, the lifetime is the total sum of those durations. If multiple groups have the same longest lifetime, the method should return all such groups in ascending order of their IDs.

For example, if we have a log string as follows: "1 create 09:00, 2 create 10:00, 1 delete 12:00, 3 create 13:00, 2 delete 15:00, 3 delete 16:00", the method will return: ["2 05:00"].

Solution Building: Step 1

First, we will split the input string into individual operations. In Java, string manipulation can be handled using methods from the String class.

import java.util.*;
import java.util.stream.Collectors;

class Solution {
    public static List<String> analyzeLogs(String logs) {
        List<String> logList = new ArrayList<>(Arrays.asList(logs.split(", ")));

Solution Building: Step 2

Next, we delve deeper into the logs. For each logged group operation in the string, we need to parse its components. These include the group ID, the type of operation (create or delete), and the time of action.

import java.util.*;
import java.util.stream.Collectors;

class Solution {
    public static List<String> analyzeLogs(String logs) {
        List<String> logList = new ArrayList<>(Arrays.asList(logs.split(", ")));

        HashMap<Integer, int[]> timeDict = new HashMap<>();  // HashMap to record the creation moment for each group in minutes
        TreeMap<Integer, Integer> lifeDict = new TreeMap<>(); // TreeMap to record the lifetime for each group in minutes

        for (String log : logList) {
            String[] parts = log.split(" ");
            int groupId = Integer.parseInt(parts[0]);
            String action = parts[1];
            String time = parts[2];
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal