📌 Day 36/150 – Combination Sum (LeetCode #39) Today’s problem was a beautiful example of recursion and backtracking — one of the most elegant problem-solving techniques in DSA. 💡 The challenge? Given a set of distinct integers and a target, find all unique combinations where the chosen numbers sum up to the target. Each number can be used unlimited times, making it a perfect fit for recursive exploration. 🔁 At first, it looks like a simple sum problem, but the real depth lies in exploring all valid combinations efficiently without duplicates. 🔹 Brute Force Idea Try every possible combination and check if it sums up to the target. ✅ Works for small inputs ❌ Exponential time – not scalable 🔹 Optimal Approach – Backtracking We use recursion to build combinations dynamically: 👉 Pick a number if it doesn’t exceed the target. 👉 Subtract it from the target and continue exploring. 👉 Backtrack once the path is complete (or invalid). This method ensures that all combinations are explored while avoiding unnecessary computations — a perfect blend of depth-first search and pruning. 🌱 🧠 Example: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Here, 2 + 2 + 3 = 7 ✅ 7 = 7 ✅ Both are valid combinations found via recursive backtracking. ⏱️ Time Complexity: O(2ⁿ) (since every number can be included/excluded) 📦 Space Complexity: O(target) (recursion depth) 💡 Learning: Backtracking problems train your brain to think systematically — exploring, deciding, and undoing choices. Understanding this pattern builds a strong foundation for tackling advanced problems like Combination Sum II, Subset Sum, and N-Queens. ♟️ Every recursive path teaches you that failure branches are just steps toward the correct solution. 🚀 #150DaysOfCode #LeetCode #ProblemSolving #Backtracking #Recursion #DSA #Cplusplus #CodingChallenge #SoftwareEngineering #TechCommunity #LearningJourney 💻
How to Solve Combination Sum with Recursion and Backtracking
More Relevant Posts
-
📌 Day 34/150 – Letter Combinations of a Phone Number (LeetCode #17) Today’s problem was a creative mix of recursion and backtracking, simulating how old phone keypads map digits to letters. ☎️ The challenge? Given a string of digits (2–9), generate all possible letter combinations that the digits could represent. At first, it looks like a simple mapping problem — just convert digits to letters. But the real task is to explore every possible combination of those letters in a systematic way. 🔹 Brute Force Idea Try every combination by using nested loops for each digit. ✅ Works for small inputs. ❌ Fails as the number of digits increases — leads to exponential growth in possibilities. 🔹 Optimal Approach – Backtracking (DFS) 👉 Key Insight: Treat each digit as a node and explore all possible letter choices for it recursively. Build combinations character by character until all digits are processed. At each step: Pick one letter from the current digit’s mapping. Recurse for the next digit. Backtrack to explore other possibilities. This ensures we cover all possible combinations efficiently and elegantly. 🧠 Example: Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] Here’s how it works: 2 → "abc" 3 → "def" We combine every letter from "abc" with every letter from "def". ⏱️ Time Complexity: O(3ⁿ × 4ᵐ) (since 7 & 9 have 4 letters each) 📦 Space Complexity: O(n) (recursion depth) 💡 Learning: Backtracking problems often feel complex, but they’re just structured explorations of possibilities. Once you visualize recursion as a decision tree, these problems become much easier to reason about. 🌳 #150DaysOfCode #LeetCode #ProblemSolving #Backtracking #Recursion #DSA #CodingChallenge #SoftwareEngineering #Cplusplus #Developers #LearningJourney #TechCommunity 🚀
To view or add a comment, sign in
-
-
📌 Day 35/150 – Remove Nth Node From End of List (LeetCode #19) Today’s problem was a classic linked list challenge that tested my understanding of two-pointer techniques — a powerful pattern for solving traversal-based problems efficiently. ⚙️ The task? Given the head of a linked list, remove the n-th node from the end and return the updated list. At first glance, it seems simple — just find the node from the end and delete it. But the twist lies in doing it in a single pass for optimal performance. 🚀 🔹 Brute Force Idea Traverse the list once to count total nodes, then again to remove the (length–n)th node. ✅ Easy to implement ❌ Requires two passes → not optimal 🔹 Optimal Approach – Two Pointer Technique To achieve this in one pass, we use two pointers: fast and slow. 👉 Move the fast pointer n steps ahead. 👉 Then move both fast and slow together until fast reaches the end. 👉 The slow pointer will be just before the target node — remove it cleanly. This elegant trick ensures we traverse the list only once! 🧠 Example: Input: head = [1, 2, 3, 4, 5], n = 2 Output: [1, 2, 3, 5] Here, the 2nd node from the end (4) is removed using the one-pass logic. ⏱️ Time Complexity: O(L) 📦 Space Complexity: O(1) 💡 Learning: Linked list problems often look tricky because of pointer manipulation, but patterns like slow & fast pointers simplify them beautifully. Recognizing and reusing such patterns across problems is a major step in mastering DSA. 💪 #150DaysOfCode #LeetCode #ProblemSolving #LinkedList #TwoPointer #CodingChallenge #SoftwareEngineering #DSA #Cplusplus #Developers #TechCommunity #LearningJourney 🚀
To view or add a comment, sign in
-
-
🥷 Day 164 of My 365 LeetCode Challenge is done! 💥 Kicked off strong, solved my problem, and the coding vibe is awesome! 🧠 💡 LeetCode 1625 — Lexicographically Smallest String After Applying Operations Today’s challenge was an interesting blend of string manipulation, BFS traversal, and modular arithmetic — the kind of problem that truly sharpens both your algorithmic thinking and pattern recognition skills. 🧠✨ We’re given a numeric string s and two integers a and b. Two operations can be performed repeatedly in any order: 1️⃣ Add a to all digits at odd indices (with digits wrapping around modulo 10). 2️⃣ Rotate the string to the right by b positions. The goal? 🔍 Find the lexicographically smallest string possible after performing any number of these operations. Sounds simple, right? But here’s the catch — since operations can be performed infinitely, the problem hides a state-space exploration challenge. The same string can appear multiple times via different paths, so blindly iterating could easily lead to infinite loops or redundant computations. ⚙️ Approach & Thought Process: To systematically explore all possible transformations, I used Breadth-First Search (BFS) — perfect for enumerating all reachable states in minimal steps. 🔸 Step 1: Start from the original string and push it into a queue. 🔸 Step 2: For each string, perform both allowed operations: - Add a to digits at odd indices (handling digit wraparound using (digit + a) % 10). - Rotate the string by b positions. 🔸 Step 3: Use a set to track all previously visited strings to prevent cycles. 🔸 Step 4: Continuously compare and update the smallest lexicographic string seen so far. Once the queue is exhausted, the smallest recorded string is our answer ✅ 🔥 Key Learning: This problem elegantly demonstrates how graph traversal (BFS) can be applied beyond traditional graphs — even on state transformations of strings. Recognizing this pattern is a huge step toward mastering advanced algorithmic thinking. ✨ Every problem like this one is a reminder that great coding isn’t about memorizing — it’s about seeing structure where others see chaos. #LeetCode #CPlusPlus #CodingChallenge #ProblemSolving #Algorithms #BFS #SoftwareEngineering #Programming #LearningJourney #CodeNewbie #DataStructures
To view or add a comment, sign in
-
-
✨ Day 40 of 50 Days Challenge ✨ Solved LeetCode 107: Binary Tree Level Order Traversal II 👉 Problem Statement: Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). 📌 Example: Input: root = [3, 9, 20, null, null, 15, 7] Output: [[15, 7], [9, 20], [3]] 🔎 Approach Used: ➡️ Breadth-First Search (BFS) using Queue 1️⃣ If the root is null, return an empty list 2️⃣ Use a queue to traverse the tree level by level 3️⃣ Store values of each level in a temporary vector 4️⃣ Reverse the final result to get bottom-up order ✅ Complexity Analysis: Time Complexity: O(n) — each node visited once Space Complexity: O(n) — queue stores all nodes at the widest level 🕒 Result: ✔️ Runtime: 2 ms (Beats 27.12%) ✔️ Memory: 16.02 MB (Beats 24.64%) 📈 Note: While the solution is optimal in time complexity, there's room to optimize memory usage further. Every step in the #CodingJourney teaches something new! 🚀 #LeetCode #Day40 #50DaysChallenge #BinaryTree #BFS #LevelOrderTraversal #CPlusPlus #DSA #CodingJourney #DevLife #KeepLearning #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 59 of LeetCode 150 Days Challenge — Copy List with Random Pointer 🔁 #LeetCode #DSA #LinkedList #Pointers #DeepCopy #Cplusplus #ProblemSolving #CodingChallenge #LearnDSA #SDE #SDEPrep #SoftwareEngineering #DSAChallenge #LeetCode150 Today’s challenge was a deep dive into Linked Lists — but with a twist. Each node doesn’t just have a next pointer, but also a random pointer that can point to any node (or even NULL) in the list. The goal: 👉 To create a deep copy of this linked list — every node, every pointer, everything cloned perfectly! 💡 My Thought Process: While solving this, I realized that if we try to copy nodes and assign their randoms immediately, we might run into an issue — what if the random pointer points to a node that hasn’t been created yet? So, I decided to build it in two phases: 1️⃣ First, create a mapping between original nodes and their copies. ->while traversing if we find node->random in our map we assign its copy to our node. 2️⃣ Then, reconnect all the next and random pointers using that mapping. ->if we missed any nodes in the first step because of their node->random not created before them. I intentionally kept some redundancy in my code to clearly demonstrate each step — because understanding pointer flow is more important than optimizing too early. At the end of the day, it’s all about "How many different ways you can think for a single problem". ⚙️ Complexity Analysis: ⏱ Time Complexity: O(N) 💾 Space Complexity: O(N) Even though it’s slightly redundant, it shows a clear step-by-step pointer mapping process — which is crucial for deep copy problems. 🧩 Key Takeaway: This problem helped me understand how to handle complex pointer relationships and build a deep copy from scratch. Sometimes, writing extra steps isn’t inefficiency — it’s clarity in learning 🔥
To view or add a comment, sign in
-
-
Don’t dive into LeetCode before you know this. It can save 40% of your time… 👇 I wasted weeks because I didn’t know this. What changed? 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱 𝗖++ 𝗦𝗧𝗟 (𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝗯𝗿𝗮𝗿𝘆). 🧠 Why it matters: STL saves you from writing complex data structures from scratch. Everything — from sorting to searching — is already optimized and tested. 𝗜𝘁 𝗵𝗮𝘀 𝟰 𝗺𝗮𝗶𝗻 𝗽𝗮𝗿𝘁𝘀: ➝ Containers (the data structures) ➝ Algorithms (the actions, like sort()) ➝ Iterators (the “pointers” that move through them) ➝ Functions (we’ll skip this for now) ⚡ 𝗟𝗲𝘁’𝘀 𝗱𝗶𝘃𝗲 𝗶𝗻𝘁𝗼 𝗖𝗼𝗻𝘁𝗮𝗶𝗻𝗲𝗿𝘀 — 𝗠𝗼𝘀𝘁 𝗨𝘀𝗲𝗱 (𝗶𝗻 𝗼𝗿𝗱𝗲𝗿): ➝ vector – dynamic array, most common → vector<int> v = {1,2,3}; ➝ unordered_map – fastest key-value lookups → unordered_map<string,int> mp; ➝ map – sorted key-value pairs ➝ set – unique sorted elements ➝ unordered_set – unique, unsorted, faster ➝ deque – insert/remove from both ends ➝ list – doubly linked list ➝ stack / queue / priority_queue – specific use (LIFO/FIFO) ➝ array – fixed size, static 💡 𝗤𝘂𝗶𝗰𝗸 𝗧𝗶𝗽𝘀: ➝ Use vector by default unless you have a reason not to. ➝ Use unordered_map when you need speed, map when you need order. ➝ set and unordered_set are perfect for unique elements. 📌 Save this post — you’ll need it every time you start a DSA problem 🚀 #cplusplus #stl #dsa #programming #codingjourney #developers #techstudents #leetcode #students #engineeringlife #competitiveprogramming
To view or add a comment, sign in
-
-
Day 26 of #50DaysLeetCodeChallenge 🧩 Problem: 561. Array Partition Today’s problem was a refreshing one — an Easy-level LeetCode challenge that reinforces how sorting and pairing can optimize outcomes. It’s one of those problems that looks simple but beautifully demonstrates the power of greedy algorithms. 🧠 Thought Process: 🔹 The task is to group integers into pairs such that the sum of the smaller element in each pair is maximized. 🔹 Sorting the array ensures each pair is as balanced as possible. 🔹 Once sorted, we simply take every alternate element (starting from index 0), since that will always represent the smaller element in each optimal pair. 🔹 This method eliminates unnecessary complexity and ensures maximum total sum. ⚙️ My Approach: 🔸 Sort the array using Arrays.sort(nums). 🔸 Initialize sum = 0. 🔸 Loop through the array with a step of 2, adding nums[i] to the sum each time. 🔸 Return the final sum — the maximum possible result. 📈 Performance: ✅ Accepted ⚡ Runtime: 17 ms (Beats 13.97%) 💾 Memory: Efficient and clean implementation 💡 Reflection: Sometimes, simplicity is the key to optimization. Even without complex data structures, understanding the problem’s core logic can lead to elegant solutions. Each day’s challenge sharpens both reasoning and coding clarity. Grateful to Trainer Shishir chaurasiya and PrepInsta for guiding me through consistent, concept-driven learning in DSA 🙏 #LeetCode #50DaysLeetCodeChallenge #ProblemSolving #Java #AlgorithmDesign #CodingChallenge #PrepInsta #DeveloperJourney #LogicBuilding #DSA #CleanCode #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 19/50 | LeetCode Coding Challenge Today's problem: Maximum Frequency After Operations - A challenging medium-level problem that tested my optimization skills! 💡 The Challenge: Given an array and k operations, we can add values in range [-k, k] to selected indices. The goal? Maximize the frequency of any element. 🎯 Key Learnings: 1️⃣ Binary Search Optimization: Replaced O(n²) nested loops with binary search using lower_bound/upper_bound - reduced complexity from O(n²) to O(n log n) 2️⃣ Two-Pointer Technique: Implemented sliding window to efficiently find valid ranges where elements can be transformed 3️⃣ Integer Overflow Awareness: Used long long for calculations with values up to 10⁹ to prevent overflow errors 4️⃣ Multiple Strategies: Combined two approaches: Keeping existing values unchanged Transforming all elements to a new target value ⚡ The Result: ✅ 633/633 test cases passed ✅ Time complexity: O(n log n) ✅ Optimized from TLE to accepted solution 🔥 Biggest Takeaway: When you hit Time Limit Exceeded, don't give up! Analyze your bottlenecks: Identify nested loops → Consider binary search or two pointers Watch for repeated computations → Use preprocessing Always handle edge cases (overflow, boundary conditions) The journey from brute force to optimal solution taught me more than just getting it right the first time ever could. Day 19 ✅ | 31 more days to go 💪 Shishir chaurasiya and PrepInsta #100DaysOfCode #CodingChallenge #LeetCode #DSA #ProblemSolving #SoftwareEngineering #CPlusPlus #Algorithms #TechJourney #LearningInPublic
To view or add a comment, sign in
-
-
💡 Day 7 of #30DaysOfDSA One Extra Pointer That Changes Everything — Types of Linked Lists Explained 🔗 When I first learned about Linked Lists, I thought they were all the same — just nodes connected in a line. But then came Singly, Doubly, and Circular linked lists… and suddenly, I realized how one small design change can completely alter how a structure behaves. Let’s break it down 👇 1️⃣ Singly Linked List Each node points only to the next node. Simple, memory-efficient — but one-way traffic only. Perfect for stacks, queues, or simple data traversal. ✅ Easy to implement ❌ Can’t move backward 2️⃣ Doubly Linked List Each node points to both the next and previous node. More memory usage, but gives you bidirectional movement — like navigating back and forth in your browser history. Head → [10 | *] → [20 | *] → [30 | NULL] ✅ Easier insert/delete from both ends ❌ Slightly higher memory cost 3️⃣ Circular Linked List Here, the last node connects back to the first, forming a loop. Perfect for cyclic operations like task scheduling or media playlists that restart automatically. [10] → [20] → [30] ↑ ↓ ←------------- ✅ Endless traversal without NULL ❌ Must handle loops carefully to avoid infinite cycles What I love about this topic is how it teaches an engineering mindset — There’s no one-size-fits-all structure. It’s always about trade-offs: speed vs memory, simplicity vs flexibility. #DSA #30DaysOfDSA #LinkedList #SinglyLinkedList #DoublyLinkedList #CircularLinkedList #DataStructures #LearnInPublic #Programming #DeveloperCommunity #Java #CodeNewbie #ComputerScience #ProblemSolving #CSFundamentals #SoftwareEngineer #CodingJourney #TechLearning #InterviewPreparation #SoftwareDevelopment #Engineering #TechSeries #CareerGrowth #CodeEveryday #KnowledgeSharing #TechJourney #Algorithms
To view or add a comment, sign in
-
🚀 Day 93 of #100DaysOfLeetCode — Minimum Operations to Convert All Elements to Zero (Leetcode 3542) Today’s problem was a fun one that really tests your understanding of array manipulation and pattern observation! 🧩 Problem: Given an array of non-negative integers, the goal is to find the minimum number of operations needed to make all elements 0. In each operation, you can select a subarray and set all occurrences of the minimum non-zero element in that subarray to 0. 💭 Example: nums = [3, 1, 2, 1] ✅ Output → 3 ⚙️ Brute Force Approach: Iterate through the array and repeatedly find the smallest non-zero number. Set all its occurrences to zero. Count operations until all elements become zero. 🔹 Time Complexity: O(n²) 🔹 Space Complexity: O(1) ⚡ Optimal Approach (Used in my Solution): Use a stack-like logic or greedy approach to count how many unique increasing non-zero elements exist in the array. Each unique segment of increasing non-zero values corresponds to one operation. 🧠 Key Idea: If the next element is larger than the previous one, it represents a new operation zone. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(n) 🔍 Dry Run Example: Input: [0, 2] Skip zeros. 2 is non-zero → stack is empty → push it and increment operation count. ✅ Result = 1 💡 Key Learnings: Observing array patterns helps to reduce redundant operations. Always analyze monotonic properties for greedy optimization. Stack logic can simplify subarray-based operation problems. 🔥 Tech Used: C++ | Arrays | Stack | Greedy 🧠 Concepts: Array traversal, Greedy Reduction, Monotonic Stack #LeetCode #Day93 #100DaysOfCode #DSA #CodingChallenge #CPlusPlus #Algorithms #ProblemSolving #GreedyAlgorithm #LearningEveryday #TechWithAnurag #CodeNewbie #SoftwareEngineering #FAANGPrep
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