Code Logo

Queue Size

Published at25 Jul 2026
Basic Queue Easy 1 views
Like0

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

Example 1
Input
[1,2,3]
Output
3
Explanation

Three elements

Example 2
Input
[]
Output
0
Explanation

Empty

Example 3
Input
[5]
Output
1
Explanation

Single

Example 4
Input
[0]
Output
1
Explanation

Zero is still an element

Example 5
Input
[10,20,30,40,50]
Output
5
Explanation

Five elements

Algorithm Flow

Recommendation Algorithm Flow for Queue Size

Solution Approach

Return the length of the array, which represents the current size of the queue.

function solution(arr) {
  return arr.length;
}

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

java
class Solution {
    public int solution(int[] nums) {
        return nums.length;
    }
}