🚀 Day 22/100 – DSA Challenge Today’s problem: Climbing Stairs (LeetCode | Easy | DP) The problem is simple: You can climb either 1 or 2 steps at a time. How many distinct ways are there to reach the top? 🔴 Approach 1: Recursion (Brute Force) 👉 At each step, you have 2 choices: Take 1 step Take 2 steps 📌 Java Code: class Solution { public int climbStairs(int n) { if (n <= 2) return n; return climbStairs(n - 1) + climbStairs(n - 2); } } ⚡ Complexity: Time: O(2ⁿ) ❌ (recomputes subproblems) Space: O(n) (recursion stack) 🟡 Approach 2: Memoization (Top-Down DP) 👉 Store results of subproblems to avoid recomputation 📌 Java Code: class Solution { public int climbStairs(int n) { int[] dp = new int[n + 1]; return helper(n, dp); } private int helper(int n, int[] dp) { if (n <= 2) return n; if (dp[n] != 0) return dp[n]; dp[n] = helper(n - 1, dp) + helper(n - 2, dp); return dp[n]; } } ⚡ Complexity: Time: O(n) ✅ Space: O(n) 🟢 Observation: This problem is essentially the Fibonacci sequence: f(n) = f(n-1) + f(n-2) 🎯 Key Learning: Start with recursion to understand the problem, then optimize using DP to eliminate overlapping subproblems. 📈 Day 22 done—getting better at recognizing DP patterns! #100DaysOfCode #DSA #DynamicProgramming #Java #CodingJourney
Climbing Stairs Problem Solution with DP
More Relevant Posts
-
🚀 Day 45/60 – DSA Challenge Today’s problem was about searching in a Rotated Sorted Array using Binary Search 🔍 🔍 Problem Solved: Given a rotated sorted array, efficiently find the index of a target element. 🧠 Approach I Used: Instead of directly applying binary search, I broke the problem into two steps: 1️⃣ Find the pivot (rotation point) using binary search 2️⃣ Apply binary search on the correct half of the array Left half → sorted from start to pivot-1 Right half → sorted from pivot to end ⚡ Key Insight: By identifying the pivot, the problem becomes two simple binary searches Careful boundary checks (like target >= nums[0]) ensure we search in the correct half Handling edge cases (like pivot at index 0) is crucial for correctness 📈 Complexity: Time: O(log n) Space: O(1) 🎯 What I Learned: Complex problems can often be simplified by breaking them into smaller parts Binary Search is not just about searching—it’s about understanding structure Boundary conditions can make or break your solution Debugging edge cases today made the concept even clearer 💡 #Day45 #DSAChallenge #BinarySearch #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 85 of #100DaysOfCode Solved 106. Construct Binary Tree from Inorder and Postorder Traversal on LeetCode 🔗 🧠 Key Insight: 👉 Postorder = Left → Right → Root 👉 Last element in postorder = root of tree 👉 Inorder = Left → Root → Right 👉 Use inorder to split into left & right subtrees ⚙️ Approach (HashMap + Recursion): 1️⃣ Take last element of postorder 🔹 This is the root 2️⃣ Find root index in inorder 🔹 Split inorder into: • Left subtree • Right subtree 3️⃣ Build subtrees recursively: 🔹 Important order: 👉 Build right subtree first, then left (because we are consuming postorder from end) 4️⃣ Use a HashMap: 🔹 Store inorder value → index 👉 For O(1) lookup ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #BinaryTree #Recursion #DivideAndConquer #HashMap #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Day 10/30 — DSA Challenge 🚀 Problem: Construct Binary Tree from Inorder and Postorder Traversal Topic: Tree + Recursion + Hashing Difficulty: Medium Approach: Used postorder to identify root node (last element) Used inorder to split tree into left and right subtrees Stored inorder indices in a HashMap for fast lookup Built tree recursively (right subtree first, then left) Mistake / Challenge: Initially confused about traversal order Made mistake by building left subtree first instead of right Fix: Understood that postorder processes (Left → Right → Root) So while constructing → build Right first, then Left Key Learning: Preorder → Root first Postorder → Root last Always align recursion order with traversal type Time Taken: 50 minutes Consistency check ✅ See you on Day 11. GitHub Repo: https://lnkd.in/gHW9vKUf #DSA #LeetCode #Java #Trees #Recursion #LearningInPublic
To view or add a comment, sign in
-
-
Day 9/ #100DaysOfCode Solved LeetCode 1848: Minimum Distance to the Target Element. Approach: The problem can be solved using a straightforward linear traversal. Iterate through the array and check for indices where the value equals the target. For each such index, compute the absolute difference between the current index and the given start index. Maintain a variable to track the minimum distance encountered during the traversal. Solution Insight: Initialize a variable with a large value (e.g., Integer.MAX_VALUE). Traverse the array once. Whenever the target element is found, update the minimum distance using Math.abs(i - start). Return the minimum value after the loop. Complexity: Time Complexity: O(n) Space Complexity: O(1) Result: 72/72 test cases passed with optimal runtime performance. This problem reinforces the importance of simple iteration and careful tracking of minimum values in array-based problems. #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
Day 76/100 Completed ✅ 🚀 Solved LeetCode – Search a 2D Matrix (Java) ⚡ Implemented an optimized binary search approach by treating the 2D matrix as a flattened sorted array. Converted 1D index into 2D coordinates (row = mid / m, col = mid % m) to efficiently locate the target in O(log(m × n)) time. 🧠 Key Learnings: • Applying binary search on a 2D matrix • Converting 1D index to 2D (row & column mapping) • Reducing time complexity from O(m × n) → O(log(m × n)) • Importance of problem observation (matrix behaves like sorted array) 💯 This problem strengthened my understanding of binary search variations and how to apply it beyond simple 1D arrays. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #binarysearch #arrays #optimization #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 Day 7: Cracking the "Two Pointer" Pattern 🚀 Today, I dived into LeetCode 167 (Two Sum II) to master the Two Pointer technique! While the standard Two Sum problem is often solved with a Hash Map, a Sorted Array gives us a secret advantage. By using two pointers—one at the start and one at the end—we can find the target sum in $O(n)$ time and $O(1)$ space. No extra memory needed! 🧠 💡 Key Takeaway: The magic happens in the movement: Sum < Target? Move the left pointer to grab a larger value. Sum > Target? Move the right pointer to grab a smaller value. Pro Tip: Always watch out for 1-indexed requirements! Adding that +1 to your return indices is the difference between a "Wrong Answer" and "Accepted." ✅ 🛠️ The Logic (Java): Java while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } One week down, more patterns to go! Following the roadmap from the "25 DSA Patterns" series. 📈 #DSA #LeetCode #CodingChallenge #Java #TwoPointers #SoftwareEngineering #Consistency
To view or add a comment, sign in
-
-
Day 22/100 — Lambda Expressions ⚡ From 5 lines of anonymous class → to just 1 clean line using lambdas. Before: new Runnable() { public void run() { println("Hi"); } }; After: () -> println("Hi"); Same output. ~80% less code, more readability. 💡 Why it matters: Lambdas make your code concise, functional, and easier to maintain—especially when working with collections. 🔹 Common Forms: → No params: () -> code → One param: x -> code → Two params: (x, y) -> code 🔹 Examples: names.sort((a, b) -> a.length() - b.length()); names.forEach(n -> println(n)); names.removeIf(n -> n.length() < 4); 🎯 Challenge: Sort a list by length first, then alphabetically when lengths are equal 👇 names.sort((a, b) -> { if (a.length() == b.length()) { return a.compareTo(b); } return a.length() - b.length(); }); Clean. Powerful. Interview-ready. 🚀 #Java #Lambda #Java8 #CoreJava #100DaysOfCode #100DaysOfJava #Programming #Developers
To view or add a comment, sign in
-
-
🚀 LeetCode — Problem 18 | Day 16 💡 Problem: 4Sum 🧠 Problem: Given an array nums and a target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that their sum equals the target. 🧠 Approach (Sorting + Two Pointers): Sort the array: Essential for two-pointer movement and skipping duplicates. Nested Loops: Fix the first two elements using two loops (i and j). Two Pointers: Use left and right pointers for remaining two elements. Skip Duplicates: Avoid duplicate quadruplets by skipping same values for i, j, left, right. ⚙️ Core Logic: Fix i and j, then set left = j + 1 and right = n - 1. Compute sum = nums[i] + nums[j] + nums[left] + nums[right]. If sum == target: Add quadruplet to result and move both pointers while skipping duplicates. If sum < target: Move left++ If sum > target: Move right-- ⏱ Time Complexity: O(n^3) 📦 Space Complexity: O(1) (excluding output list) ⚠️ Edge Cases: - Array size < 4 - Integer overflow (use long for sum) - Duplicate values leading to repeated results 🔍 Insight: 4Sum is an extension of 3Sum. Fixing two numbers reduces problem to two-pointer search. 🔑 Key Learning: - Extending two-pointer technique to higher dimensions - Handling duplicates efficiently in sorted arrays - Using long to avoid overflow "Use sorting and nested two pointers to reduce complexity from O(n^4) to O(n^3) while ensuring unique quadruplets." #LeetCode #DSA #Java #TwoPointers #CodingJourney #4Sum #Algorithms
To view or add a comment, sign in
-
-
Day 41 of Daily DSA 🚀 Solved LeetCode 20: Valid Parentheses ✅ Problem: Given a string containing only (), {}, [], determine if the input string is valid. Rules: Open brackets must be closed by the same type Open brackets must be closed in the correct order Every closing bracket must have a matching opening bracket Approach: Used a Stack to track opening brackets and validate matching pairs. Steps: Traverse the string Push opening brackets onto the stack For closing brackets → check top of stack If it matches → pop Else → return false At the end, stack should be empty ⏱ Complexity: • Time: O(n) • Space: O(n) 📊 LeetCode Stats: • Runtime: 3 ms (Beats 87.41%) ⚡ • Memory: 43.37 MB A classic stack problem that builds strong fundamentals for expression parsing & validation. #DSA #LeetCode #Java #Stack #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
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