TIP102 Unit 3 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
movies
, where each element represents the number of movies a user wants to stream, and an integer k
representing the index of the user we are interested in.k
to finish streaming all their movies.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a queue to simulate the streaming process, keeping track of each user's remaining movies and the total time until the user at position k
finishes streaming.
1. Initialize an empty deque (queue).
2. Populate the queue with tuples `(i, movies[i])`, where `i` is the index of the user and `movies[i]` is the number of movies they want to stream.
3. Initialize a `time` variable to keep track of the time taken.
4. While there are users in the queue:
1. Dequeue the first user and increment the `time` by 1 as they stream one movie.
2. If this user is at index `k` and has just streamed their last movie, return the `time`.
3. If the user still has movies left to stream, decrease their movie count by 1 and enqueue them back to the end of the queue.
5. Return the `time` when the loop exits (though logically, the return should happen inside the loop).
⚠️ Common Mistakes
k
before they leave the queue.from collections import deque
def time_required_to_stream(movies, k):
# Initialize an empty queue
queue = deque()
# Populate the queue with (index, movie_count) tuples
for i in range(len(movies)):
queue.append((i, movies[i]))
time = 0
while queue:
i, movie_count = queue.popleft() # Get the current user and their movie count
time += 1 # Increment time as the user streams one movie
if i == k and movie_count == 1:
# If this is user k and they've just streamed their last movie, return the time
return time
if movie_count > 1:
# If the user has more movies to stream, reduce their count and put them back in the queue
queue.append((i, movie_count - 1))
return time # In case something goes wrong, although we should always return within the loop