Understanding BFS with Queue and Deque in Python

Today I went down a rabbit hole: Queue + BFS 🕳️🐇 I started with a question: 🧐 When people say BFS, why do they always bring up a queue? Here’s what I learned: ✅ Queue basics (Python): Queue = FIFO (first in, first out) 🚶♂️➡️🚶♀️ In Python, collections.deque is the right tool because popleft() is O(1) ⚡ list.pop(0) looks similar, but it becomes O(n) because everything shifts left 🐢 ✅ What BFS is actually doing: BFS explores a graph level by level 🪜 Start node → all nodes 1 step away → then 2 steps away → and so on. That “level order” is exactly why BFS uses a queue. ✅ The big missing piece: seen/visited 👀 Without seen, cycles can make BFS loop forever 🔁😬 So marking nodes as visited (usually when enqueuing) keeps traversal correct and efficient. 🤔 Fun detail: neighbor order changes traversal order A: [B, C] vs A: [C, B] → same BFS, different visitation sequence. #Python #DSA #BFS #Queue #Deque #Algorithms #InterviewPrep #BackendEngineering

  • timeline

To view or add a comment, sign in

Explore content categories