Given an array representing a queue, return the number of elements currently in the queue. The size is simply the length of the array.
For example, a queue containing [10, 20, 30] has size 3. An empty queue has size 0. A queue with a single element [5] has size 1. The size changes as elements are pushed (increases) or popped (decreases).
The size operation is one of the fundamental queue operations alongside enqueue (push), dequeue (pop), and peek (front). Knowing the current size is essential for queue management — it tells you whether the queue is empty, whether it has room for more elements, and how many items are waiting to be processed.
In array-based queue implementations, the size is just the array length, which is an O(1) operation in most languages. In linked-list-based queues, the size is typically maintained as a separate counter that is incremented on enqueue and decremented on dequeue, also O(1). Some implementations may calculate size by traversing the list, which would be O(n).
This is a straightforward operation that demonstrates the concept of tracking the number of elements in a data structure — a concept that extends to stacks, lists, sets, and all other collections.
Example Input & Output
Three elements
Empty
Single
Zero is still an element
Five elements
Algorithm Flow
Solution Approach
Return the length of the array, which represents the current size of the queue.
The size of a queue equals the number of elements in the underlying array. Most languages store the length as a property that can be read in O(1) time (JavaScript's .length, Java's .length, Python's len(), PHP's count()). This avoids iterating through all elements, which would be O(n).
In a production queue implementation, the size is typically maintained as a separate counter that is incremented on enqueue and decremented on dequeue. This makes the size operation O(1) regardless of the underlying data structure, whether array-based or linked-list-based.
Time complexity is O(1), space complexity is O(1). The operation does not modify the queue.
Best Answers
class Solution {
public int solution(int[] nums) {
return nums.length;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
