Day 70 of #100DaysOfCode Today I solved "Unique Binary Search Trees" on LeetCode using Recursion + Dynamic Programming (Memoization). Key Idea: For n nodes, we try every value as the root. If a value root is chosen: Left subtree can be formed using (root − 1) nodes Right subtree can be formed using (n − root) nodes The total number of BSTs for that root becomes: left_subtrees × right_subtrees By summing this for all possible roots, we get the total number of unique BSTs. To avoid recomputing the same subproblems, I used memoization. Concepts Used: • Recursion • Dynamic Programming • Memoization • Binary Search Tree properties Time Complexity: O(n²) Space Complexity: O(n) This problem is a classic example of the Catalan Number pattern in dynamic programming. Step by step, building stronger intuition for DP and tree-based problems. #100DaysOfCode #DSA #LeetCode #DynamicProgramming #BinaryTree #Cpp #CodingJourney
Unique Binary Search Trees Solved with Recursion and Memoization
More Relevant Posts
-
🚀 DSA Day 47 – LeetCode Problem 300: Longest Increasing Subsequence (LIS) Today’s problem was a classic and super important one in Dynamic Programming 📈 🔍 Problem Insight: Given an array of integers, the goal is to find the length of the longest strictly increasing subsequence. 💡 Key Approaches: 1️⃣ Dynamic Programming (O(n²)) For each element, check all previous elements Build a dp[] array where dp[i] stores LIS ending at index i 2️⃣ Optimized Binary Search Approach (O(n log n)) Maintain a temporary list (tails) Use binary search to replace elements and keep the list sorted Length of this list = LIS length ⚡ Why optimization works? We don’t need the actual subsequence — just the length. So we maintain the smallest possible tail for increasing subsequences of each length. 🧠 What I Learned: Difference between brute DP and optimized approach Using binary search in unexpected ways Importance of LIS in many advanced problems 💻 Time Complexity: DP: O(n²) Optimized: O(n log n) 📦 Space Complexity: O(n) Slowly building strong fundamentals 💪 — consistency > intensity! #DSA #LeetCode #DynamicProgramming #BinarySearch #CodingJourney #100DaysOfCode #TechGrowth
To view or add a comment, sign in
-
-
🚀 Day 10 of 100 Days LeetCode Challenge Problem: Find All Possible Stable Binary Arrays II Today’s problem is an extension of Day 9—but with optimized Dynamic Programming ⚡ 💡 Key Insight: Same constraints: Fixed number of 0s and 1s No more than limit consecutive identical elements 👉 Which means: We must carefully control streak length And efficiently count all valid combinations 🔍 Approach (Optimized DP): Use DP + Prefix Sum Optimization State includes: Count of 0s used Count of 1s used Ending with 0 or 1 💡 Optimization: Instead of recalculating ranges repeatedly, use prefix sums This reduces time complexity significantly 👉 Apply modulo (10⁹ + 7) for large answers 🔥 What I Learned Today: Same problem can have multiple levels of optimization Prefix sum is powerful in reducing DP transitions Moving from brute → DP → optimized DP is real growth 📈 📈 Challenge Progress: Day 10/100 ✅ Double digits achieved! LeetCode, Dynamic Programming, Prefix Sum, Optimization, Combinatorics, Binary Arrays, DSA Practice, Coding Challenge, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #DynamicProgramming #PrefixSum #Optimization #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
🚀 LeetCode — Day 23 Solved: Word Break Today’s problem was a solid introduction to Dynamic Programming on strings. Approach: • Use a DP array where dp[i] indicates if the substring s[0...i-1] can be formed • For each position, check all words in the dictionary • If a valid split is found → mark it as true Key idea: Break the problem into smaller subproblems and reuse previously computed results. This problem really shows how DP helps turn an exponential recursion into a polynomial solution. Also reinforces thinking in terms of: “Can I build this string step by step from known valid parts?” Day 23. Still building consistency. 🔁🔥 #LeetCode #Day23 #DSA #DynamicProgramming #ProblemSolving #Consistency #Cpp #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day 10 of my coding consistency journey. Today I solved LeetCode Problem 1018 – Binary Prefix Divisible By 5. The task is to check whether the binary number formed at each prefix is divisible by 5. 💡 My Approach: • Instead of forming large binary numbers, I kept track of the current value modulo 5. • For each bit, I updated the value using: num = (num * 2 + current_bit) % 5 • If the result becomes 0, it means the current prefix is divisible by 5. • I stored the result for each prefix in a boolean array. This approach avoids overflow and keeps the solution efficient. Problems like this highlight the importance of modular arithmetic in optimization. Consistency is slowly turning into strength 🚀 #LeetCode #DSA #Algorithms #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 10 of #30DaysOfLeetCode Solved #21 – Merge Two Sorted Lists on LeetCode using C. Problem: Given two sorted linked lists, merge them into a single sorted linked list by rearranging the existing nodes. Approach: • Used an iterative approach with a dummy node • Maintained a pointer to build the merged list • Compared values from both lists and attached the smaller node • Moved the corresponding pointer forward • After traversal, attached the remaining nodes from either list Performance: • Runtime: 0 ms (Beats 100% ) • Memory: 11.37 MB Key Learnings: • Strong understanding of linked list manipulation • Importance of dummy nodes to simplify logic • Learned how to merge efficiently without extra memory • Reinforced the concept of pointer handling in C #LeetCode #DSA #Algorithms #CProgramming #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
Pattern Recognition Mastery on Day 224 Today Today I focused on a very important skill in competitive programming which is pattern recognition. Understanding the keywords in a problem description can help you choose the right data structure immediately. When I see words like subarray or substring combined with a window I know it is a Sliding Window problem. If the question asks for the maximum or minimum value in that window I know I need to use a Deque to keep the solution efficient. I applied this logic to solve LeetCode 239 which is the Sliding Window Maximum problem. Instead of checking every window from scratch I used a monotonic decreasing deque. This allows me to keep track of the largest elements in linear time. The core idea is to remove indices from the back of the queue if the new number is larger than the old ones. This ensures that the largest value is always at the front of the queue. Once the window moves past an index I simply remove it from the front. Learning these rules helps me solve hard problems much faster. It is all about building a mental rule book for different types of array and string challenges. LeetCode question solved today: 215 Sliding Window Maximum #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #SlidingWindow #Deque #PatternRecognition #AlgorithmDesign #ProblemSolving #DataStructures #LogicBuilding #CodingChallenge #SoftwareEngineering #ProgrammingDaily #WebDevelopment #TechLearning #JSAlgorithms #CleanCode #InterviewPrep #SoftwareDeveloper
To view or add a comment, sign in
-
🚀 Day 9 of Daily LeetCode Challenge Yesterday I solved the Longest Increasing Subsequence (LIS) problem using the classic Dynamic Programming approach with O(n²) time complexity. Today I revisited the same problem and optimized it using Binary Search, reducing the time complexity to O(n log n). 💡 Approach (Optimized): Maintain a dp array where dp[i] stores the smallest possible tail of an increasing subsequence of length i+1. For every number in the array: If it is greater than the last element in dp, extend the subsequence. Otherwise, use binary search to find the first element in dp that is ≥ current number and replace it. This keeps dp sorted and allows efficient updates. 📈 Result: Improved the solution from O(n²) → O(n log n) while maintaining correctness. #LeetCode #DSA #Algorithms #BinarySearch #DynamicProgramming #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 23/50 – LeetCode Challenge 🧩 Problem: Pascal’s Triangle Today’s problem focused on generating Pascal’s Triangle, a classic example that strengthens understanding of patterns and dynamic programming concepts. 📌 Problem Summary: Given an integer numRows, generate the first numRows of Pascal’s Triangle. Each element in the triangle is the sum of the two elements directly above it. Example: [1] [1,1] [1,2,1] [1,3,3,1] 🔍 Approach Used ✔ Started with the first row [1] ✔ For each new row: First and last elements are always 1 Middle elements = sum of two elements from previous row ✔ Built the triangle row by row ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(n²) 💡 Key Learning ✔ Identifying patterns in problems ✔ Building solutions step by step ✔ Understanding dynamic programming intuition ✔ Working with nested loops effectively A simple problem that builds strong foundational thinking for more complex DP problems. Consistency is the key to improvement 🚀 🔗 Problem Link: https://lnkd.in/gjVfC6Kf #50DaysOfLeetCode #LeetCode #DSA #DynamicProgramming #Arrays #ProblemSolving #CodingJourney #FutureAIEngineer #Consistency
To view or add a comment, sign in
-
-
Heaps and K-Related Problems Day 217 Today Today is day 217 of my coding challenge. I focused on using Heaps and Priority Queues to solve problems more efficiently. A very important rule I learned today is that when a question asks for the kth smallest or kth largest element, you should use a heap. The trick is to keep the heap size restricted to K. This makes the code much faster than simple sorting. I solved LeetCode 215 which is about finding the Kth largest element in an array. Instead of sorting the whole array which takes O(n log n), I used a Min-Priority Queue of size K. This reduced the time complexity to O(n log k). I also worked on LeetCode 703 where I had to find the kth largest element in a data stream. A Min-Heap is perfect here because the smallest element in a heap of size K is always the kth largest overall. For LeetCode 1046 called Last Stone Weight, the simple way uses repeated sorting which is very slow. I optimized it using a Max-Priority Queue to get a speed of O(n log n) because it always keeps the heaviest stones at the top. Another interesting problem was LeetCode 347, Top K Frequent Elements. I used a frequency map and then a Min-Priority Queue to keep only the top K frequent items. This is better than sorting because it avoids sorting elements we do not need. Finally I solved LeetCode 378 which is the Kth Smallest Element in a Sorted Matrix. Using a Min-Heap helped me find the right value efficiently by only looking at the necessary rows and columns. Using heaps is a game changer for performance especially when dealing with large amounts of data. LeetCode Questions i solved: LeetCode 215 LeetCode 703 LeetCode 1046 LeetCode 378 LeetCode 347 #DSAinJavaScript #365daysOfCoding #JavaScriptDeveloper #LeetCodeSolutions #DataStructures #AlgorithmDesign #LogicBuilding #ProblemSolving #JavaScriptProgramming #TechLearning #HeapDataStructure #PriorityQueue #CodingInterview #SoftwareEngineering #KthLargest #Optimization #CleanCode #JavaScriptLogic #CareerGrowth #ProgrammingJourney
To view or add a comment, sign in
-
Day 81 - LeetCode Journey 🚀 Solved LeetCode 2: Add Two Numbers (Medium) — a classic linked list problem that beautifully combines arithmetic with pointer manipulation. At first, it looks like simple addition. But the twist is that numbers are stored in reverse order as linked lists, and we must simulate digit-by-digit addition. 💡 Core Idea (Simulation + Carry Handling): Traverse both linked lists simultaneously Add corresponding digits along with carry Create a new node for each digit of the result Move forward until both lists and carry are exhausted A dummy node helps in building the result list smoothly. 🤯 Why it works? Because we mimic the exact process of manual addition, handling carry at each step, ensuring correctness even when lengths differ. ⚡ Key Learning Points: • Converting real-world logic into code (digit addition) • Handling carry efficiently • Traversing two linked lists together • Using dummy node for clean construction • Managing different list lengths gracefully • Achieving O(max(n, m)) time and O(1) extra space This problem strengthens both logical thinking and linked list handling. Also, this pattern connects with: Add Binary Multiply Strings Linked List arithmetic problems Big integer calculations ✅ Better understanding of simulation problems ✅ Stronger pointer + arithmetic combination ✅ Improved handling of edge cases (carry, unequal lengths) From simple addition to linked list manipulation — this is where logic meets implementation 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
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