What if adding and subtracting numbers could lead to the same target? ➕➖ Let’s decode how. Hey everyone! Day 319 of my 365-day coding journey brought me face-to-face with one of the most interesting dynamic programming problems — LeetCode 494: Target Sum. This problem is a fantastic blend of recursion, logic, and optimization through DP. Let’s dive in. ⚡ 🛠️ The Problem You’re given an integer array nums and a target value. By assigning either a “+” or “−” sign before each number, the goal is to count how many different expressions can evaluate to the given target. Example: nums = [1, 1, 1, 1, 1], target = 3 → Output = 5 (There are 5 ways to assign symbols to reach 3.) 🎯 The Approach I solved this using two approaches — starting from the basics and optimizing it further. Solution 1: Recursion (Brute Force) I used a recursive function that tries adding and subtracting each element to explore all possible combinations. This clearly demonstrates the problem’s structure but leads to exponential time complexity (O(2^N)). Solution 2: 1D Dynamic Programming To optimize, I transformed the problem into a subset-sum variation. By using a 1D DP array, I tracked how many ways we can achieve each possible sum. This reduced the complexity to O(N * Sum), making it scalable for larger inputs. 🧠 Key Takeaways 💡 Many DP problems start with recursion — identifying overlapping subproblems helps in building optimized solutions. 🧩 Transforming a problem (like Target Sum → Subset Sum) can often reveal a cleaner, more efficient path. ⚙️ 1D DP arrays save space without compromising clarity or performance. 💬 Challenge for You! How do you usually transition from recursion to dynamic programming? What’s your mental model for identifying patterns like this? 📺 Watch My Full Walkthrough I explain both the recursive and optimized DP solutions step-by-step in my latest video: https://lnkd.in/gE9Ma7uA 🔥 Join the Conversation If you’re exploring dynamic programming or solving LeetCode challenges daily, let’s connect and grow together! 🚀 #CodingJourney #DSA #DynamicProgramming #LeetCode #ProblemSolving #TargetSum #Recursion #Algorithms #CodeNewbies #DeveloperLife #Programming #LearningEveryDay #365DaysOfCode
Subbareddy karri’s Post
More Relevant Posts
-
Hi Everyone, Many of us find asynchronous (async) programming difficult to understand. Today, I’ll try to simplify the concept of async programming in an easy and practical way 😊 Before that, let’s first understand synchronous programming. 🔹 Synchronous Programming Synchronous programming means that a program runs step by step, where each operation must complete before the next one starts. Let’s look at a simple example: user_id = input("Enter user id: ") show_loading() # UI code to show loading bar get_user_data(user_id) # External API call close_loading() # UI code to hide loading bar Imagine you have an application where: A loading bar is shown An external API is called to fetch user data Here’s what happens: show_loading() starts the loading animation When get_user_data() is called, it blocks the entire program The UI freezes ❌ until the API responds Only after the API call completes does the loading bar stop This happens because synchronous code blocks I/O operations, preventing other tasks from running. 🔹 Solving This with Async Programming Now let’s see how async programming helps: user_id = input("Enter user id: ") show_loading() # UI code to show loading bar await get_user_data(user_id) # External API call close_loading() # UI code to hide loading bar Notice the use of await before get_user_data(). What changes here? The API call is moved to the event loop While waiting for the response, the program does not block The UI remains responsive ✅ Other background tasks can continue running This may look like parallel execution, but it’s actually concurrent, not parallel. The CPU is not kept idle while waiting for the API response—instead, it can handle other tasks ⚡ 🔹 When Should You Use Async Programming? Async programming is most useful when dealing with: External API calls 🌐 File or network I/O Database operations Any system or external resource where response time is unpredictable In such cases, async helps improve performance, responsiveness, and user experience. I hope this explanation helps clarify async programming. Happy coding! 🚀 #Python #PythonAsync #AsyncAwait #ProgrammingConcepts #APIDevelopment #BackendDevelopment #SoftwareEngineering #WebDevelopment #DeveloperCommunity #LearnToCode #TechExplained #CodingTips
To view or add a comment, sign in
-
Can you reverse only specific characters in a string without breaking the rest? 🧩 Let’s solve it smartly. Hey everyone! Day 350 of my 365-day coding journey, and today’s problem was a classic string manipulation challenge: LeetCode 345, Reverse Vowels of a String. This problem is simple on the surface but great for exploring multiple approaches and understanding trade-offs in efficiency. Let’s get into it. ✨ 🛠️ The Problem Given a string, the task is to reverse only the vowels in it while keeping all other characters in their original positions. Vowels include both lowercase and uppercase: a, e, i, o, u. Example: Input: IceCreAm Output: AceCreIm 🎯 The Approaches I solved this problem using three different methods: Solution 1: Brute Force First, collect all vowels from the string. Reverse the collected vowels. Traverse the string again and replace vowels in order. This approach is easy to understand but uses extra space. Solution 2: Two Pointers Use two pointers, one starting from the left and one from the right. Move them inward until both point to vowels, then swap. This is the most optimal approach with constant extra space. Solution 3: Stack Push all vowels into a stack. Traverse the string again and replace vowels by popping from the stack. This naturally reverses the vowels and keeps the logic clean. 🧠 Key Takeaways String problems often look easy but can be solved in many ways with different space and time trade-offs. The two-pointer technique is extremely powerful for in-place string manipulation. Understanding multiple approaches helps in choosing the right solution during interviews and real-world coding. 💡 Challenge for You! Which approach do you usually prefer for string problems — clarity first or optimal performance? Share your thoughts below. 💬 📺 Watch My Video Walkthrough I explain all three approaches step by step in my latest video: https://lnkd.in/gSZZbnx9 🔥 Join the Conversation If you’re consistently solving DSA problems or working towards mastering coding interviews, let’s connect and grow together. 🚀 #CodingJourney #DSA #LeetCode #Strings #TwoPointers #ProblemSolving #Algorithms #DataStructures #Python #DeveloperLife #CodeNewbies #Programming #365DaysOfCode #LearningEveryDay
To view or add a comment, sign in
-
-
💻 Day 56 of my DSA Journey: 0/1 Knapsack — Recursion & Decision Making 🎒🔥 Today I worked on one of the most fundamental Dynamic Programming problems — the 0/1 Knapsack, which strengthens understanding of recursive choices, constraints, and optimization. 🧩 Problem Statement Given: int[] weight = {1, 2, 3, 4}; int[] value = {5, 10, 15, 20}; int capacity = 7; // bag capacity Each item can be picked only once (0/1 rule). 🎯 Goal: Maximize total value without exceeding the bag capacity. ✅ Output Maximum value = 35 👉 Optimal selection: Pick items with weights 3 and 4 Total weight = 7 Total value = 15 + 20 = 35 🔑 Core Idea (Recursive Thinking) At every item index, we make two decisions: ✔ Include the item (if weight allows) ✔ Exclude the item Then recursively solve for the remaining items and capacity. choice = max( include current item, exclude current item ) 🧠 Key Learnings ✔ How recursion explores include vs exclude choices ✔ Why order does not matter in 0/1 Knapsack ✔ How constraints (capacity) prune recursion paths ✔ Why overlapping subproblems lead to DP optimization ✔ Difference between 0/1 Knapsack vs combinations/subsets 🌳 Recursion Insight Each item creates two branches Forms a decision tree Final answer comes from the maximum value path ⏱️ Complexity ⏳ Time: O(2ⁿ) — brute-force recursion 📦 Space: O(n) — recursion stack (Optimizable to O(n × W) using DP / memoization) 🌱 What I Gained Today ✔ Strong intuition for decision-based recursion ✔ Clear understanding of optimization problems ✔ Why knapsack is a foundation for many DP problems ✔ How recursion naturally leads to dynamic programming 🔖 Hashtags #DSA #Java #Knapsack #DynamicProgramming #Recursion #Backtracking #ProblemSolving #CodingJourney #100DaysOfCode #Day56
To view or add a comment, sign in
-
-
I refactored some business logic, cleaned up the code… and accidentally changed what the software does. In this video, I go through the mistakes I made, why they’re so easy to introduce during refactoring, and why passing tests and good coverage don’t automatically mean your logic is correct. Especially when business rules are involved, assumptions sneak in fast. This one is less about a specific bug and more about a reality of software engineering: there often is no single ground truth. Not in the code, not in the tests, and not in the requirements. If you’ve ever felt slightly uneasy after a "successful" refactor, this will probably look familiar. Watch the video here: https://lnkd.in/ej-VFrz4 #softwareengineering #refactoring #cleanCode #python #testing #softwareDesign #programming #developers
To view or add a comment, sign in
-
-
I refactored some business logic, cleaned up the code… and accidentally changed what the software does. In this video, I go through the mistakes I made, why they’re so easy to introduce during refactoring, and why passing tests and good coverage don’t automatically mean your logic is correct. Especially when business rules are involved, assumptions sneak in fast. This one is less about a specific bug and more about a reality of software engineering: there often is no single ground truth. Not in the code, not in the tests, and not in the requirements. If you’ve ever felt slightly uneasy after a "successful" refactor, this will probably look familiar. Watch the video here: https://lnkd.in/erZQ7w3j #softwareengineering #refactoring #cleanCode #python #testing #softwareDesign #programming #developers
To view or add a comment, sign in
-
-
Can two pointers really tell you everything about a subsequence? Let’s put it to the test. 🔍⚡ Hey everyone! Day 347 of my 365-day coding journey brought me to LeetCode 392: Is Subsequence — a clean, practical problem that highlights the power of pointer movement and string traversal. Despite being simple on the surface, it's a great reminder of how different approaches help us understand performance trade-offs. Let’s get into it. 🛠️ The Problem Given two strings s and t, the task is to determine whether s is a subsequence of t. A subsequence means characters of s must appear in t in the same order — but not necessarily consecutively. Example: s = "abc", t = "ahbgdc" → true s = "axc", t = "ahbgdc" → false 🎯 The Approaches I explored two methods to solve this: Solution 1: Brute Force (DFS Helper Function) I used a recursive DFS-style helper function to try all possible paths through string t and match characters in order. It works, but it’s not efficient — exploring unnecessary branches and increasing time complexity. Still, it’s a valuable way to understand how subsequence checking can be modeled as a decision tree. Solution 2: Two Pointer Approach This is the optimal way to solve it. I placed one pointer on s and another on t, advancing the t pointer until characters matched. Whenever the characters aligned, the pointer on s moved forward. If the pointer on s reaches the end, s is a subsequence. Clean, efficient, and intuitive — the kind of solution you’d use in real-world scenarios. 🧠 Key Takeaways 🔹 Brute force teaches you problem structure, recursion flow, and backtracking. 🔹 Two pointers give you the fastest and simplest solution — perfect for interviews. 🔹 Understanding both approaches helps build confidence in pattern recognition for string-based problems. 💡 Challenge for You! Have you tried solving subsequence problems using dynamic programming, recursion, or greedy methods? Which approach made the most sense to you? Share below! 💬 📺 Check out my video walkthrough I break down both approaches in detail in my latest video: https://lnkd.in/geg8XVXs 🔥 Join the Conversation If you're exploring DSA, solving LeetCode, or building consistency through daily challenges, let’s connect! The journey is always better when shared. 🚀 #CodingJourney #DSA #TwoPointers #Strings #LeetCode #ProblemSolving #Algorithms #DataStructures #Programming #TechLearning #DeveloperLife #CodeNewbies #365DaysOfCode #LearningEveryDay
To view or add a comment, sign in
-
-
I fought LeetCode 410, and the Dynamic Programming almost won. 🏳️ It was 11 PM. My coffee was cold. My confidence was lower than the stock market in 2008. I was staring at LeetCode 410: Split Array Largest Sum. If you haven't seen this problem, it looks innocent. It’s like a wolf in sheep’s clothing, except the wolf is an O(N^2⋅K) time complexity and the sheep is a "Hard" tag. The Problem: You have an array of integers (non-negative). You need to split it into k subarrays. You want to minimize the largest sum among these subarrays. My Brain (Phase 1): The Over-Engineering Phase 🤓 "Ah," I whispered to my empty room. "This is classic Dynamic Programming. I will create a 2D memoization table that tracks the index and the number of cuts remaining. I am a genius." I wrote the code. It was beautiful. It was elegant. I hit submit. LeetCode Judge: Time Limit Exceeded. My beautiful DP solution was too slow. The interviewer (in my imagination) was shaking their head. My imaginary offer letter was shredding itself. The Pivot (Phase 2): The "Wait, What?" Phase 🤨 I stared at the constraints. N is up to 1000. DP is usually fine for that... unless... Then I saw the pattern. The pattern that separates the "Coding Gods" from the "People crying into their keyboards" (me). Binary Search on Answer. "But wait!" you scream. "The array isn't sorted! You can't Binary Search an unsorted array! That’s illegal! That’s against the laws of physics!" Hold on. Put the pitchforks down. We aren't binary searching the Array. We are binary searching the Universe of Answers. 🌌 Think about it: What is the smallest possible maximum sum? It's the largest single element in the array (because you can't cut an element in half). What is the largest possible maximum sum? It's the sum of the entire array (if k=1). The answer is somewhere between max(nums) and sum(nums). Let's say the range is [10, 50]. Is the answer 30? I don't know. Let's ask a Greedy algorithm to check. "Hey Mr. Greedy, can you split this array into K parts where no part is bigger than 30?" If yes -- Great! Try 29. (Minimize it further). If no -- Too tight! Try 31. (We need more room). We just turned a nightmare DP problem into a guessing game. It’s literally the "Higher or Lower" game you played as a kid, but for securing a $200k job offer. The Takeaway: Sometimes, when you're stuck looking for the needle in the haystack (the array), stop looking at the hay. Look at the needle. If the answer space is monotonic... just binary search the answer. It feels like cheating. It feels like magic. But it works. I just recorded a video where I break this down visually so you don't have to suffer through the "DP Phase" like I did. I explain the Check Function logic in a way that even my grandma would understand (maybe). #LeetCode #SoftwareEngineering #CodingInterviews #BinarySearch #DeveloperLife #TechHumor
To view or add a comment, sign in
-
🚀 Why Object-Oriented Programming (OOP) Matters? Object-Oriented Programming isn’t just a coding style — it’s a way of thinking. 💡 OOP helps developers build software that is: Organized 🧩 Reusable ♻️ Scalable 📈 Easy to maintain 🔧 By using core concepts like: Encapsulation → protect data Inheritance → reuse code Polymorphism → write flexible logic Abstraction → focus on what matters OOP turns complex problems into real-world models, making applications closer to how we think and work. ✨ From web applications to large enterprise systems, OOP is the backbone of clean and powerful software design. #OOP #Programming #SoftwareEngineering #CleanCode #LearningJourney #Tech
To view or add a comment, sign in
-
-
💡 Day 37 | Longest Palindromic Subsequence (Dynamic Programming) Today I solved a beautiful DP problem — Longest Palindromic Subsequence, where the goal is to find the length of the longest subsequence in a string that reads the same forwards and backwards. A classic problem that teaches bottom-up thinking and subproblem dependency building. 🧮 Operation Given a string s, find the longest palindromic subsequence (LPS) — a sequence that may skip characters but must maintain order and form a palindrome. 🔑 Key Idea Use a 2D Dynamic Programming table dp[i][j]: dp[i][j] → length of LPS in substring from index i to j Rules: If characters match: dp[i][j] = 2 + dp[i+1][j-1] If they don't match: dp[i][j] = max(dp[i+1][j], dp[i][j-1]) Base case: every single character is a palindrome → dp[i][i] = 1 Fill the table diagonally from smaller substrings to bigger ones. 🌱 Concepts Used Dynamic Programming Subsequence Logic Overlapping Subproblems Bottom-Up Matrix Filling String Processing ⏱ Time Complexity O(n²) — we fill an n×n DP table. 📦 Space Complexity O(n²) — standard 2D DP. 🎯 Takeaway This problem teaches how breaking a task into smaller overlapping subproblems can reveal patterns that are not obvious at first glance. Dynamic Programming helps manage choices efficiently — especially when comparisons span both ends of a string. 🔖 #Day37 #StringDSA #Java #DynamicProgramming #CodingJourney
To view or add a comment, sign in
-
-
Recursion is one of those concepts that looks elegant in code, and confusing in your head. A function calling itself feels unnatural at first. But once the mental model clicks, recursion becomes one of the cleanest ways to solve problems involving hierarchy, repetition, and divide-and-conquer logic. In this article, I break recursion down step by step: • What recursion actually is (without hand-waving) • Base cases, recursive cases, and why both matter • How the call stack really works • Classic examples like factorial and Fibonacci • Why naïve recursion can be slow, and how memoization fixes it • Why trees and recursion are a perfect match If recursion has ever felt “magical” or intimidating, this guide is meant to make it practical and approachable. #Programming #SoftwareEngineering #ComputerScience #Recursion #Java #Algorithms #Coding #DeveloperEducation
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