⭐Day 34 of #100DaysOfCode⭐ 🚀 Leveling Up: Solving the "Cheapest Flights Within K Stops" Challenge 🔍 Behind the Logic: My Approach In my Java implementation, I used a Breadth-First Search (BFS) approach to navigate the flight network efficiently. ✨ Here is a breakdown of the steps I took: 1️⃣Adjacency List Construction: I first transformed the flight data into an adjacency list to allow for quick lookups of neighboring cities and their respective costs. 2️⃣Level-Order Traversal (BFS): I utilized a Queue to explore the paths. Since we have a stop limit K, BFS is ideal because it allows us to process the graph level by level (stop by stop). 3️⃣Cost Optimization: I maintained a minCost array to track the cheapest way to reach each city. I only added a flight to my queue if the new path offered a lower cost than a previously recorded one. ⭐Constraint Management: By keeping track of the number of levels (stops) processed, I ensured the algorithm stopped as soon as we exceeded K stops, keeping the solution both accurate and efficient. 💯If you're stuck on a problem today, remember: The "Accepted" status is just the destination, but the true growth happens in the debugging. Keep coding, keep learning! 🚀 #LeetCode #Java #DataStructures #Algorithms #ProblemSolving #SoftwareEngineering #CodingJourney #BFS Anchal Sharma Ikshit ..
Solving Cheapest Flights Within K Stops Challenge with BFS in Java
More Relevant Posts
-
📘 DSA Journey — Day 37 Today’s focus: Binary Search with APIs / decision functions. Problems solved: • Guess Number Higher or Lower (LeetCode 374) • First Bad Version (LeetCode 278) Concepts used: • Binary Search • Decision-based search (using API feedback) • Search space reduction Key takeaway: Both problems are classic examples of binary search on answers using an external API. In Guess Number Higher or Lower, we use the guess() API: • If guess is too high → move left • If too low → move right • If correct → return mid In First Bad Version, we use the isBadVersion() API: • If current version is bad → search left to find the first occurrence • Else → search right The key idea is: We don’t know the exact value, but we can narrow down the search space based on feedback. This pattern is useful in problems where: • A condition is monotonic (false → true transition) • We need to find the first/last occurrence of a condition Time complexity remains O(log n). Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 14 of #100DaysOfCode Problem Solved: 3783. Mirror Distance of an Integer Small problems often hide powerful insights. Today’s challenge revolved around understanding how numbers behave when reversed and measuring the difference between the original and its mirror form. Approach The solution is built on a straightforward idea: Reverse the given integer using mathematical operations. Calculate the absolute difference between the original number and its reversed value. Instead of relying on string conversion, I focused on a digit-by-digit reversal approach, which keeps the logic efficient and avoids unnecessary space usage. Complexity Time Complexity: O(d), where d is the number of digits Space Complexity: O(1), constant extra space Key Learnings Even simple number manipulation problems strengthen core logic. Avoiding extra space can lead to cleaner and more optimized solutions. Consistency in solving problems daily builds strong problem-solving intuition. Every day adds a small improvement — and those small improvements compound over time. #100DaysOfCode #DSA #Java #ProblemSolving #CodingJourney #LeetCode #Consistency #Learning
To view or add a comment, sign in
-
-
🚀 Day 44 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Find the Least Frequent Digit Problem Insight: Find the digit (0–9) that appears the least number of times in a given number. Approach: • Used a frequency array of size 10 to store digit counts • Extracted digits using modulo and division • Traversed the frequency array to find the minimum occurring digit • Returned the smallest digit in case of tie Time Complexity: • O(n) Space Complexity: • O(1) (fixed size array of 10) Key Learnings: • Arrays are more efficient than HashMap when range is limited • Digit extraction using % 10 is very useful in number problems • Keeping track of minimum efficiently avoids extra passes Takeaway: Simple logic + right data structure = clean and optimal solution #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
📘 DSA Journey — Day 31 Today’s focus: Binary Search for boundaries and square roots. Problems solved: • Sqrt(x) (LeetCode 69) • Search Insert Position (LeetCode 35) Concepts used: • Binary Search • Search space reduction • Boundary conditions Key takeaway: In Sqrt(x), the goal is to find the integer square root. Using binary search, we search in the range [1, x] and check mid * mid against x to narrow down the answer. This avoids linear iteration and achieves O(log n) time. In Search Insert Position, we use binary search to find either: • The exact position of the target, or • The correct index where it should be inserted The key idea is that when the target is not found, the final position of the left pointer gives the correct insertion index. These problems highlight how binary search is not just for finding elements, but also for determining positions and boundaries efficiently. Continuing to strengthen fundamentals and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 27 – #100DaysOfLeetCode Challenge Today I solved the problem “Best Time to Buy and Sell Stock II.” Problem Summary: You are given an array prices where prices[i] is the price of a stock on day i. The goal is to maximize profit by buying and selling the stock multiple times. However, you must sell before you buy again. Approach – Greedy Strategy Instead of trying every possible transaction combination, the idea is simple: 🔹 If the next day's price is higher than today's price, we take the profit 🔹 Add all positive price differences 🔹 This captures every profitable opportunity in the price trend For example: If prices = [7,1,5,3,6,4] Profits = (5-1) + (6-3) = 7 Time Complexity: O(n) Space Complexity: O(1) Key Learning: A Greedy approach works well when we want to capture every incremental profit opportunity instead of trying complex combinations. Continuing my journey of strengthening Data Structures & Algorithms skills through the #100DaysOfLeetCode challenge. On to the next problem! #100DaysOfLeetCode #LeetCode #DSA #GreedyAlgorithm #ProblemSolving #Java #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 43 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Sum of Unique Elements Problem Insight: Find elements in an array that appear exactly once and calculate their total sum. Approach: • Used a frequency array to count occurrences of each number • Traversed the array to build frequency • Added only those elements to sum whose frequency is exactly 1 Time Complexity: • O(n) Space Complexity: • O(1) (fixed size array used for constraints) Key Learnings: • Frequency array is faster than HashMap when range is fixed • Two-pass approach makes logic clear and simple • Always check constraints before choosing data structure Takeaway: Right data structure makes the solution simple and efficient 🚀 #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 47of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Mirror Distance of an Integer Problem Insight: Given a number, the task is to find the absolute difference between the original number and its reversed form. Approach: • Stored the original number in a temporary variable • Reversed the number using digit extraction (modulo and division) • Calculated the absolute difference between the original and reversed number Time Complexity: O(d), where d = number of digits Space Complexity: O(1) Key Learnings: • Digit manipulation using modulo and division is a powerful technique • Always store the original value before modifying the input • Reversing numbers is a fundamental pattern in many DSA problems Takeaway: Breaking the problem into simple steps makes even tricky-looking logic easy to solve. #DSA #Java #LeetCode #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 564 of #750DaysOfCode 🚀 🔍 LeetCode 3488 – Closest Equal Element Queries (Medium) Today’s problem was a really interesting mix of hashing + binary search + circular array logic — exactly the kind of question that tests both intuition and optimization skills. 💡 Problem Summary: Given a circular array nums and some query indices, for each query we need to find the minimum circular distance to another index having the same value. 🧠 Key Insight: Instead of checking every index (which would be too slow ❌), we: Store all indices of each number using a HashMap Use binary search to quickly find the closest neighbors Handle circular distance using: 👉 min(|i - j|, n - |i - j|) ⚡ Optimized Approach: Preprocess indices → O(n) Each query → O(log n) Overall → Efficient for large constraints (1e5) 📌 What I Learned: Circular arrays often require thinking in modulo arithmetic Preprocessing + binary search can drastically reduce complexity Always check edge cases (single occurrence) 🔥 Problems like this remind me that optimization is not about writing more code, but about thinking smarter. #LeetCode #Java #DSA #CodingJourney #ProblemSolving #HashMap #BinarySearch #Tech #SoftwareEngineering #LearnInPublic #Consistency
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