Today I worked on Codédex Daily Challenge #17, a Python problem focused on decision-making under constraints. The challenge was to choose the best flight voucher based on the highest dollars-per-hour-delayed ratio, while excluding any option that exceeded the maximum waiting time. At first, the solution looked straightforward: Iterate through each option, calculate the ratio, and keep the best one. But while testing the code, I found an important edge case. My initial implementation initialized best_ratio = 0, which caused a bug when I tested inputs where all valid voucher values produced a ratio of 0. In that situation, the code returned -1 instead of returning the first valid option, even though the problem statement specified that ties should return the first one. That small error reinforced a valuable lesson: writing code is not only about solving the main case, but also about identifying boundary conditions and making sure the logic holds under all valid inputs. From a computational perspective: Time complexity: O(n) — each option is evaluated once Space complexity: O(1) — only a few tracking variables are needed What I like about challenges like this is that they reflect real-world thinking: we are often comparing value, time, and constraints to make better decisions. This kind of logic can easily connect to: cost-benefit analysis prioritization models scoring systems operational decision-making analytics-driven recommendations A simple bug, but a very real reminder: edge cases matter. #Python #ProblemSolving #Debugging #DataAnalytics #Optimization #CodeDex #ContinuousLearning
Python Challenge: Identifying Edge Cases in Decision-Making
More Relevant Posts
-
DevLog Day 15. Started with Search in a 2D Matrix from NeetCode 150. The array is sorted both row wise and column wise and you need to find if a target element exists. My first instinct was to grab the first element of each row, run binary search on those to find the right row, then binary search within that row using columns. Turned out that was the right call and I solved it with O(log(m*n)) TC which is the expected solution. Good feeling when the first instinct is correct. Then I moved to Plus One on LeetCode. Easier problem but I overcomplicated my first approach. I converted the array to an integer using exponentials, added one, then converted it back. It worked and got accepted but was not efficient. The better approach is cleaner. Traverse the array in reverse and look for the first non 9 digit. If you find one just increment it and return. If the digit is 9 turn it to 0 and keep going. In the worst case where every digit is 9 like in 999 you just prepend a 1 and return 1000. Best case is O(1), worst case is O(n), single pass. Should have thought of this myself but at least I understand it now. After DSA I covered Caching in System Design. The core idea is to store frequently requested data closer to where it is needed so you avoid hitting the database every time. There are three layers, device level caching, server level caching and database level caching. In practice good systems use all three together and the performance difference is significant. And to round out the day I went through Python OOP concepts. Classes, objects, the fundamentals. Getting comfortable here before I start solving machine coding problems more seriously in Python. #DevLog #BuildInPublic #DSA #NeetCode #BinarySearch #SystemDesign #Python #LearningInPublic #IndieHacker #WebDevelopment
To view or add a comment, sign in
-
Everyone learns stacks. But very few understand where they actually matter. Take a simple problem: Checking if brackets are balanced. Most people think it’s about counting. It’s not. It’s about order. Here’s what really happens behind the scenes: → You scan the expression left to right → Every opening bracket goes into a stack → Every closing bracket tries to match the last opening one If it matches → remove it If it doesn’t → the entire structure breaks That’s the moment you realize: Stacks aren’t just data structures. They are decision systems. They enforce rules like: Last In → First Out And that’s exactly how: • Code editors validate syntax • Compilers detect errors • Browsers manage navigation history A simple example: [(a+b)] → Valid ✔ [(a+b] → Invalid ❌ Same characters. Different structure. That’s the difference between working code and broken logic. The lesson? In programming — and in systems — structure beats quantity. Always. #DataStructures #Python #ProblemSolving #CodingJourney #AIThinking
To view or add a comment, sign in
-
Built a simple Linked List from scratch in Python to strengthen core DSA fundamentals. Key operations implemented: • Insert at beginning • Insert at end • Insert at specific position Clean and minimal implementation 👇 💡 Tips & insights from this implementation: • Always handle edge cases first (especially position == 0 and empty list) • Use position - 1 when inserting → you need the previous node, not the exact index • Traversal safety matters → always check temp is None to avoid crashes • Keep functions single responsibility (traverse_to_position makes insertion cleaner and reusable) • Don’t break links accidentally → Always connect new_node.next before changing temp.next • Naming matters → insert_behind can be clearer as insert_end • Remember: Linked Lists are about pointer management, not index access like arrays Simple idea, powerful foundation #DSA #SoftwareEngineering
To view or add a comment, sign in
-
-
💻 Solved a great problem today: Count Increasing Subarrays 🚀 Given an array, the task was to count all strictly increasing subarrays of size ≥ 2. 🔍 Approach I used: Broke the array into continuous increasing segments For each segment of length k, calculated subarrays using the formula: 👉 k(k-1)/2 Summed all results to get the final answer ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 💡 This problem helped me understand how breaking a problem into patterns can simplify complex logic. Here’s my Python solution 👇 class Solution: def countIncreasing(self, arr): list2 = [] list2.append(arr[0]) list3 = [] for i in range(1, len(arr)): if arr[i-1] < arr[i] and arr[i] > 2: list2.append(arr[i]) else: list3.append(list2) list2 = [] list2.append(arr[i]) list3.append(list2) ans = 0 for i in list3: if len(i) > 1: ans += (len(i) * (len(i) - 1)) // 2 return ans 🔥 Always learning, always improving. #python #dsa #coding #problemSolving #programming #developers #learning
To view or add a comment, sign in
-
-
🚀 Mastering the art of loops! 🔄 Discover how loops help your code execute repetitive tasks efficiently. Essentially, loops are like a magical chant that tells your program to keep doing something until a certain condition is met. For developers, mastering loops is crucial for automating tasks and iterating over data structures with ease. Here's the breakdown: 1️⃣ Initialize a counter variable 2️⃣ Set the condition for the loop 3️⃣ Define the action to perform in each iteration Sample code using a "for" loop in Python: ``` for i in range(5): print("Hello, World!") ``` 🌟 Pro Tip: Use loops to reduce redundancy in your code and boost efficiency. 💡 ⚠️ Common Mistake: Forgetting to update the counter variable in the loop, leading to an infinite loop! 🔄 🌟 What's your favorite use case for loops in your projects? Let's discuss! 💬 #Coding101 #LearnToCode #TechTips #CodeNewbie #PythonProgramming #DeveloperCommunity #LoopLogic #CodeEfficiency #ProDevSkills 🌐 View my full portfolio and more dev resources at tharindunipun.lk
To view or add a comment, sign in
-
-
Day 29: The Anatomy of a Bug — Three Types of Errors 🐞 In programming, not all "crashes" are created equal. We categorize errors into three levels of severity, ranging from "The computer doesn't understand you" to "The computer does exactly what you said, but you said the wrong thing." 1. Syntax Errors (The "Grammar" Mistake) These happen before the code even starts running. Python’s "Parser" looks at your script and realizes it violates the rules of the language. The Cause: Missing colons :, unclosed parentheses (, or incorrect indentation. The Result: The program won't start at all. 💡 The Engineering Lens: These are the "cheapest" errors to fix. Your code editor (IDE) will usually highlight these with a red squiggly line as you type. 2. Runtime Errors (The "Panic" Mistake) The syntax is perfect, and the program starts running—but then it hits a situation it can't handle. The Cause: Dividing by zero, trying to open a file that doesn't exist, or calling a variable that hasn't been defined yet (NameError). The Result: The program "crashes" in the middle of execution. 💡 The Engineering Lens: We handle these using Exception Handling (try/except). Professional code assumes things will go wrong (like the internet cutting out) and builds "safety nets" to keep the program alive. 3. Semantic Errors (The "Logic" Mistake) These are the most dangerous and difficult to find. The program runs perfectly from start to finish. There are no crashes and no red text. But the output is wrong. The Cause: You used + when you meant -, or your loop stops one item too early. The Result: The program gives you the wrong answer (e.g., a calculator saying $2 + 2 = 22$). 💡 The Engineering Lens: The computer is doing exactly what you told it to do; the "error" is in your logic. We find these using Unit Testing and Debugging tools. If you don't test your code, you might not even know a semantic error exists until a customer reports it. #Python #SoftwareEngineering #Debugging #ProgrammingTips #LearnToCode #TechCommunity #PythonDev #CleanCode #BugHunting
To view or add a comment, sign in
-
🚀 Day 18 of Consistency | #75DaysLeetCodeChallenge 🧠 Today’s Problem : Valid Parentheses (#20) 💡 Key Learning: This problem builds a strong foundation in using a stack data structure to validate matching patterns in strings. ⚡ Approach: Use a stack to track opening brackets Create a mapping of closing → opening brackets Traverse the string → If opening bracket → push to stack If closing bracket → check top of stack → pop if valid Return true if stack is empty at end 🧠 Why this works: Ensures correct order of brackets Stack follows LIFO → perfect for matching pairs Efficient solution → O(n) time, O(n) space 🔥 Result : ✔️ Runtime: 0 ms (Beats 100%) 📈 This is a fundamental problem for mastering stacks and parsing logic. A big thanks to Shivam Singh, Nikhil Yadav & Akshat Tiwari for this amazing challenge 🙌 Consistency is compounding. Keep going. 💪 #Day18 #LeetCode #DSA #CodingJourney #100DaysOfCode #Python #Stack #Consistency
To view or add a comment, sign in
-
-
House Robber II - LeetCode 213 - Medium Today, I solved the House Robber II problem, which adds a circular constraint to the original challenge. In this version, all houses are arranged in a circle, meaning the first and last houses are neighbors. Breaking into both would trigger the alarm. To solve this, I used a strategy to break the circular dependency by converting it into two separate linear sub-problems. Since we cannot rob both the first and the last house, the problem can be split into two cases: one excluding the last house and one excluding the first house. By applying the standard house robber logic to both cases and taking the maximum, we find the global optimal solution. Key Learnings 1) Circular Constraint Management: Learned how to handle dependencies in a circular data structure by breaking it into linear segments. 2) Code Reusability: Reused the logic from House Robber I as a helper function to solve the two sub-problems efficiently. 3) Problem Decomposition: Observed how a complex constraint can be simplified by considering mutually exclusive scenarios. Time and Space Complexity Time Complexity: O(N) — We traverse the houses twice, resulting in a linear time complexity. Space Complexity: O(N) — We use a DP array to store the maximum profit for each sub-problem. (Note: This can be optimized to O(1) using variables). #LeetCode #DynamicProgramming #Blind75 #SDEPrep #DataStructures #Python #ProblemSolving #CodingJourney #Freshers
To view or add a comment, sign in
-
-
🚀 Day 61 of #100DaysOfCode 🧩 Problem: Word Break (LeetCode 139) Today’s problem was all about Dynamic Programming + String Matching. 💡 Problem Statement: Given a string "s" and a dictionary of words "wordDict", determine if "s" can be segmented into a space-separated sequence of one or more dictionary words. --- 🔍 Approach: Instead of checking all possible combinations (which is expensive), I used Dynamic Programming: ✔️ Create a DP array where "dp[i]" means: 👉 Can the substring "s[0:i]" be formed using the dictionary? ✔️ Initialize: "dp[0] = True" (empty string is always valid) ✔️ For every index "i", check all "j < i": If "dp[j]" is True AND "s[j:i]" exists in dictionary → mark "dp[i] = True" --- ⚡ Time Complexity: O(n²) ⚡ Space Complexity: O(n) --- 📌 Key Learning: Dynamic Programming helps avoid recomputation by storing results of subproblems. --- 🔥 Consistency is the real game. #DSA #LeetCode #Python #CodingJourney #PlacementPreparation
To view or add a comment, sign in
-
-
🚀 Solved a LeetCode Problem – Running Sum (Prefix Sum Concept) Today I solved a problem based on the Running Sum / Prefix Sum concept. 🔍 Problem Statement: Given an array, compute a new array where each element at index i represents the sum of all elements from index 0 to i. 💡 My Approach: Instead of recalculating the sum for every index (which would be inefficient), I used an incremental approach: I initialized a result list with the first element. Then, I iterated through the array starting from index 1. At each step, I updated the current element by adding the previous cumulative sum: 👉 Current element = Current value + Previous running sum I stored each updated value in the result list. This way, I reused previously computed results instead of recomputing sums again and again. ⚡ Why this is efficient? Each element is processed only once. No nested loops are used. Avoids redundant calculations. ⏱️ Complexity Analysis: Time Complexity: O(n) → Single pass through the array Space Complexity: O(n) → Extra list used to store results 📌 Key Learning: This problem helped me understand the importance of Prefix Sum technique, which is widely used in problems involving range sums, subarrays, and optimizations. 💻 Code: class Solution: def runningSum(self, nums: List[int]) -> List[int]: res=[] res.append(nums[0]) for i in range(1,len(nums)): nums[i]=nums[i]+nums[i-1] res.append(nums[i]) return res #100DaysOfCode #Python #DSA #CodingJourney #PrefixSum #ProblemSolving
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