Track Screen Time Usage - codepath/compsci_guides GitHub Wiki

Unit 4 Session 1 Advanced (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the structure of the input?

    • A: The input is a list of tuples, where each tuple contains an app name (string) and the number of minutes spent on that app (integer).
  • Q: What is the output?

    • A: The output is a dictionary where the keys are app names and the values are the total time spent on each app (in minutes).
  • Q: What should the function return if there are no logs?

    • A: The function should return an empty dictionary.
  • Q: Are there any constraints on the input, such as the app names or time values?

    • A: It is assumed that the app names are unique strings and the time values are non-negative integers.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the list of logs and aggregate the total time spent on each app using a dictionary.

1) Initialize an empty dictionary called `screen_time`.
2) For each `app, time` in `logs`:
   a) If `app` is already in `screen_time`, increment its value by `time`.
   b) If `app` is not in `screen_time`, add it with `time` as the initial value.
3) Return the `screen_time` dictionary.

**⚠️ Common Mistakes**

- Forgetting to initialize the app's total time correctly when encountering it for the first time.
- Not handling the case where the logs list is empty.

I-mplement

def track_screen_time(logs):
    screen_time = {}

    for app, time in logs:
        if app in screen_time:
            screen_time[app] += time
        else:
            screen_time[app] = time

    return screen_time