1703. Team Line
Visitors at a festival gate queue up, but friends insist on standing together. There are n people numbered 0 to n - 1, and teamOf[x] is the team of person x. Design a class TeamLine whose constructor receives the array teamOf and which supports three methods.
enqueue(x) puts person x directly behind the last person of the same team who is currently in the line; if nobody of that team is in the line, x goes to the very end. dequeue() removes the person at the front of the line and returns that person's number, or -1 if the line is empty. size() returns how many people are in the line. A person is never enqueued while already in the line, but may be enqueued again after being dequeued. Each call should take O(1) expected time; keep one queue per team plus a queue that remembers the order in which teams entered the line. Space is O(n).
Example 1
- Input:
- operations = ["TeamLine","enqueue","enqueue","enqueue","size","dequeue","dequeue","dequeue","dequeue"]arguments = [[[0,1,0,1]],[0],[1],[2],[],[],[],[],[]]
- Output:
- [null,null,null,null,3,0,2,1,-1]
- Explanation:
Persons 0 and 2 share team 0, so after enqueuing 0, 1, 2 the line is 0, 2, 1 and the dequeues return 0, 2, 1, then -1.
Example 2
- Input:
- operations = ["TeamLine","dequeue","enqueue","enqueue","enqueue","enqueue","dequeue","enqueue","dequeue","dequeue","size"]arguments = [[[5,5,7,7,5]],[],[2],[0],[3],[4],[],[1],[],[],[]]
- Output:
- [null,-1,null,null,null,null,2,null,3,0,2]
- Explanation:
Dequeue on an empty line gives -1; after enqueuing 2, 0, 3, 4 the line is 2, 3, 0, 4 (3 joins 2 and 4 joins 0), and later person 1 slots in behind 4.
Example 3
- Input:
- operations = ["TeamLine","size","enqueue","size","dequeue","enqueue","dequeue","dequeue","size"]arguments = [[[0]],[],[0],[],[],[0],[],[],[]]
- Output:
- [null,0,null,1,0,null,0,-1,0]
- Explanation:
A single person can leave and re-enter; the last dequeue on an empty line returns -1 and the size is 0.
Constraints
1 ≤ teamOf.length ≤ 1000
0 ≤ x < teamOf.length
0 ≤ teamOf[x] < 1000
x is never enqueued while already queued
At most 2000 calls in total
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(1) expected per call
- Space
- O(n)