Tutorialspoint
Problem
Solution
Submissions

Implement a Queue Using a List

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 10

Create a Python class called Queue that implements a queue data structure using a list. The class should support standard queue operations such as enqueue, dequeue, peek, is_empty, and size. The queue should follow the First-In-First-Out (FIFO) principle.

Example 1
  • Input: queue = Queue()
  • Operations: queue.enqueue(10)
  • Operations: queue.enqueue(20)
  • Operations: queue.dequeue()
  • Operations: queue.peek()
  • Output: 10, 20
  • Explanation:
    • Step 1: Create a Queue instance.
    • Step 2: Enqueue two values.
    • Step 3: Dequeue the first value (10).
    • Step 4: Peek at the next value (20).
Example 2
  • Input: queue = Queue()
  • Operations: queue.enqueue("apple")
  • Operations: queue.enqueue("banana")
  • Operations: queue.is_empty()
  • Operations: queue.size()
  • Operations: queue.peek()
  • Operations: queue.dequeue()
  • Operations: queue.size()
  • Output: False, 2, "apple", 1
  • Explanation:
    • Step 1: Create a Queue instance.
    • Step 2: Enqueue two values.
    • Step 3: Check if queue is empty (False).
    • Step 4: Get queue size (2).
    • Step 5: Peek at first value ("apple").
    • Step 6: Dequeue first value ("apple").
    • Step 7: Get new queue size (1).
Constraints
  • The queue can contain elements of any data type.
  • Time Complexity: O(1) for all operations except dequeue which could be O(n).
  • Space Complexity: O(n) where n is the number of elements in the queue.
  • Dequeue and peek operations on an empty queue should be handled gracefully.
QueueListMicrosoftPwC
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a Python list to store the queue elements
  • For enqueue, use list.append()
  • For dequeue, consider using list.pop(0) or collections.deque for better performance
  • Implement proper error handling for operations on an empty queue
  • Consider implementing a max_size parameter (optional)

Steps to solve by this approach:

 Step 1: Create a Queue class with a list to store queue elements.

 Step 2: Implement enqueue method to add items to the end of the queue.
 Step 3: Implement dequeue method to remove and return the first item.
 Step 4: Implement helper methods like peek, is_empty, and size.
 Step 5: Test the implementation with various operations.

Submitted Code :