Codepath

Screen Time Session Management

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 strings, where each string represents an action: either "OPEN <app>" or "CLOSE <app>".
  • Q: What is the output?

    • A: The output is a boolean value: True if all app sessions are properly managed (every opened app has a corresponding close in the correct order), and False otherwise.
  • Q: What should the function return if the list is empty?

    • A: The function should return True because there are no unmatched sessions.
  • Q: Are there any constraints on the input?

    • A: It is assumed that the input only contains valid "OPEN <app>" and "CLOSE <app>" actions.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use a stack to track the apps as they are opened. For each "CLOSE <app>" action, check if the last opened app is the same; if not, return False. At the end, if the stack is empty, return True.

1) Initialize an empty list called `stack`.
2) Iterate over each `action` in `actions`:
   a) If `action` starts with `"OPEN"`, extract the app name and push it onto the `stack`.
   b) If `action` starts with `"CLOSE"`, extract the app name and check if the stack is not empty and the last opened app is the same:
      - If not, return `False`.
      - If yes, pop the app from the stack.
3) After processing all actions, return `True` if the stack is empty, otherwise return `False`.

**⚠️ Common Mistakes**

- Forgetting to check if the stack is empty before popping an app during a `"CLOSE"` action.
- Not handling the case where an app is closed before being opened.

I-mplement

def manage_screen_time_sessions(actions):
    stack = []

    for action in actions:
        if action.startswith("OPEN"):
            _, app = action.split(maxsplit=1)
            stack.append(app)
        elif action.startswith("CLOSE"):
            _, app = action.split(maxsplit=1)
            if not stack or stack[-1] != app:
                return False
            stack.pop()

    return len(stack) == 0
Fork me on GitHub