Implemented Depth-First Search (DFS) from Scratch in Python! DFS is one of the most fundamental graph traversal algorithms — think of it like navigating a maze: you pick a path and follow it all the way until you hit a dead end, then backtrack and try the next unexplored route. I implemented the iterative version using an explicit stack (preferred in production since it avoids Python's recursion depth limit). Here's how it works: 1. Push the start node onto a stack 2. Pop the top node (LIFO — last in, first out) 3. Visit all its unvisited neighbours and push them onto the stack 4. Repeat until the stack is empty Key takeaways: Time Complexity: O(V + E) — visits every vertex and edge once Space Complexity: O(V) — for the visited set + stack Used reversed() on neighbours so the traversal visits them in natural left-to-right order (since stack is LIFO, reversing ensures the first neighbour gets popped first) The stack is what makes this DFS — swap it with a queue and you get BFS! DFS vs BFS in one line: DFS goes deep before going wide (Stack / LIFO) BFS goes wide before going deep (Queue / FIFO) #Python #DataStructures #Algorithms #DFS #DepthFirstSearch #GraphAlgorithms #CodingJourney #DSA #Programming #SoftwareEngineering #LearningInPublic
Implementing Depth-First Search (DFS) in Python
More Relevant Posts
-
LeetCode Problem 1143: "Longest Common Subsequence": Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings. The below implementation in Python resolves this problem in O(m*n) time and space complexity using the dynamic programming approach. A dp array is created whose cells store the value of longest common subsequence upto a specific length of text1 and text2. At the last cell we get the value of "longest common subsequence" for the given two strings. #Python #LeetCode #DynamicProgramming #Algorithms #DataStructures #CompetitiveProgramming #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
A tiny Python trick I learned while using Claude Code While building an app with Claude Code, I noticed it repeatedly using a neat Python pattern I had somehow missed for years. d = {'A': 1, 'B': 2} e = {**d, 'A': 2} print(e) # {'A': 2, 'B': 2} This looks trivial. But the idea behind it is powerful: start from a default dictionary and selectively override fields. It’s a small trick, but it creates a very clean pattern for: ✅ Generating test cases ✅ Configuration overrides ✅ Scenario simulation Sometimes the most useful ideas are not big algorithms. They are small patterns that quietly make code cleaner. #pythonic #claudecode #claude #software #pythontricks #python
To view or add a comment, sign in
-
Python Clarity Series – Episode 12 Topic: Default Arguments Trap ⚠️ Advanced Trap: Mutable Default Arguments This looks harmless: def add_item(item, lst=[]): lst.append(item) return lst print(add_item(1)) print(add_item(2)) **Output: [1] [1, 2] ❗ Why? Because default list is created ONLY ONCE. Better way: def add_item(item, lst=None): if lst is None: lst = [] lst.append(item) return lst 💡 Deep Concept: Default arguments are evaluated once at function definition. This is NOT exam-level trick. This is real Python behavior. Strong concept = strong programmer. Did this surprise you? #PythonAdvanced #CodingMindset #DeveloperThinking
To view or add a comment, sign in
-
-
Just launched: Open Telemetry in Python — Part 1 If you've ever stared at logs at 2 AM wondering "which" service broke and "why" — this tutorial is for you. Part 1 covers the foundations: → What observability actually is (and how it differs from monitoring) → The three pillars: Traces, Metrics, and Logs → What OpenTelemetry is — and what it isn't → Your first instrumented Python app with real spans No fluff. Just clear explanations, working code, and a cheat sheet you'll actually use. 📖 Read it free at www.getspanforge.com 🔗 https://lnkd.in/geWXMD2w Parts 2–6 (Flask, Jaeger, Prometheus, the Collector) are coming soon. Follow along if you don't want to miss them. Share your comments, thank you. #OpenTelemetry #Python #Observability #SoftwareEngineering #DevOps
To view or add a comment, sign in
-
𝗤. 𝗜𝗳 𝗣𝘆𝘁𝗵𝗼𝗻 𝗛𝗮𝘀 𝗧𝗵𝗿𝗲𝗮𝗱𝘀… 𝗪𝗵𝘆 𝗗𝗼𝗲𝘀𝗻’𝘁 𝗜𝘁 𝗦𝗰𝗮𝗹𝗲 𝗼𝗻 𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗲 𝗖𝗼𝗿𝗲𝘀? When I first learned about multithreading in Python, I assumed it would use all CPU cores. It doesn’t (for CPU-heavy tasks). The reason is something called the 𝐆𝐥𝐨𝐛𝐚𝐥 𝐈𝐧𝐭𝐞𝐫𝐩𝐫𝐞𝐭𝐞𝐫 𝐋𝐨𝐜𝐤 (𝐆𝐈𝐋). 👉 The GIL ensures that only one thread executes Python bytecode at a time. So even if you create multiple threads: CPU-bound tasks won’t run in parallel They take almost the same time as a single thread But here’s the important nuance:- The GIL mainly affects 𝐂𝐏𝐔-𝐛𝐨𝐮𝐧𝐝 𝐭𝐚𝐬𝐤𝐬. For: - I/O-bound work (API calls, file reading, DB queries) - Network operations - Threading still improves performance. So how do we use multiple cores in Python? -> multiprocessing -> ProcessPoolExecutor -> Libraries like NumPy (which release GIL internally) My takeaway: 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐆𝐈𝐋 𝐜𝐡𝐚𝐧𝐠𝐞𝐬 𝐡𝐨𝐰 𝐲𝐨𝐮 𝐝𝐞𝐬𝐢𝐠𝐧 𝐬𝐲𝐬𝐭𝐞𝐦𝐬 𝐢𝐧 𝐏𝐲𝐭𝐡𝐨𝐧. #Python #TechInterview #SoftwareEngineering #LearningInPublic #SystemDesign
To view or add a comment, sign in
-
Let’s think together 👇 def change_value(x): x = x + 10 return x num = 5 change_value(num) print(num) 🤔 What do you think the output will be? Is it: 15 5 Error ✅ The correct answer is: 5 Wait… why not 15? 😏 Because in Python, integers are immutable. When we passed num into the function: The value 5 was copied into x The function modified x But the original variable num was never reassigned So num stays the same. 🔥 The real twist If we did this instead: num = change_value(num) print(num) Now the output becomes 15 Because we reassigned the returned value. 💡 Key Insight Python doesn’t magically change your variables. You must explicitly reassign them. This small concept explains: Why integers behave differently than lists Why some bugs happen silently The core idea behind mutable vs immutable objects Now your turn 👇 What do you think would happen if we used a list instead of an integer? 😏 #Python #Coding #100DaysOfCode #Programming #Backend #LearningJourney
To view or add a comment, sign in
-
Weekly Challenge 4: Binary Search (Iterative). Why search harder when you can search smarter? Use Binary Search. Imagine looking for a word in a dictionary. Do you read every page from the beginning? No. You open it in the middle and decide: "Left or Right?". That is the essence of Binary Search, and it's the focus of my coding challenge for Week 4. The Implementation: I wrote a Python script (using NumPy) that generates a random environment to test the algorithm. Key Takeaway: While a simple loop (Linear Search) checks elements one by one ($O(n)$), Binary Search cuts the problem in half with every step ($O(\log n)$). Check out the trace in the console output below to see how few attempts it takes to find the target! 👇 📂 Full code on GitHub: https://lnkd.in/ezPaaiDM #Python #BinarySearch #Algorithms #CodingChallenge #DataStructures #Engineering
To view or add a comment, sign in
-
LeetCode #217 – Contains Duplicate | Python Solution Iterating through nums, each element is checked against a HashSet — if it already exists, return True immediately; otherwise, insert it and continue. No nested loops, no redundant comparisons — just a single pass with instant lookups. 💡 Key Takeaway: Trading space for time is a core algorithmic principle. A set eliminates the need for brute-force O(n²) comparisons by giving constant-time lookups. ⏱ Time: O(n) 💾 Space: O(n) #LeetCode #DataStructures #Python #HashSet #CodingInterview #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
#Day 47 of My Python & DSA Journey Today I solved the “Check if Binary String Has at Most One Segment of Ones” problem on LeetCode. 🔍 Problem Overview: Given a binary string containing only 0s and 1s, the task is to determine whether the string contains at most one continuous segment of 1s. If multiple separated segments of 1s exist, the result should be False. 🧠 Approach: I iterated through the string and tracked how many times a new segment of 1s starts. Whenever a 1 appears either at the beginning of the string or immediately after a 0, it indicates the start of a new segment. If more than one such segment is found, the condition fails. ⚡ Key Takeaways: • Strengthened understanding of string traversal • Practiced pattern recognition in binary strings • Improved logical problem-solving using Python 📊 Complexity: • Time Complexity: O(n) • Space Complexity: O(1) Consistently solving problems helps me improve my algorithmic thinking and coding efficiency every day. Looking forward to learning more and solving tougher challenges ahead! Under the Guidance of : Rudra Sravan kumar and Manoj Kumar Reddy Parlapalli #Day47 #Python #LeetCode #DataStructures #Algorithms #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Solved the classic Two Sum problem today using Python. Instead of using the brute-force approach (O(n²)), I optimized it using a HashMap and reduced the time complexity to O(n). 🧠 Key Learnings: • Think beyond brute force * Use HashMaps for constant-time lookup * Strong fundamentals come from consistent practice Sharing my implementation on GitHub. #Python #DSA #ProblemSolving #AI #MachineLearning #Coding https://lnkd.in/gWGSyu9V
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development