🚀 Day 165 of My LeetCode Journey 🚀 494. Target Sum 🫧 In this problem, given an array of numbers and a target value. The goal is to place either a ‘+’ or ‘–’ sign in front of every number so that the final expression evaluates to the given target. ▪️ At first, it looks like we need to try all possible + and - combinations, but that would be inefficient. Instead, we can convert the problem into a subset sum problem. ▪️ If we divide the numbers into two groups, one with positive signs and the other with negative signs. ▪️ The equation becomes positive-negative = target. ▪️ After rearranging the equation, we get negative = (total - target) divided by 2. ▪️ This means the problem now becomes finding how many subsets of the array have a sum equal to (total_sum - target) / 2. ▪️ If (total - target) is negative or odd, it is impossible to form such subsets, we can immediately return 0. ▪️ To solve this, use recursion with memoization. ▪️ At every index, we have two choices, either to pick the current number or skip it. ▪️ We store intermediate results in a DP dictionary so that if the same state appears again, we don’t recalculate it. #LeetCode #DynamicProgramming #Python #CodingJourney #Day165 🔥
LeetCode 494 Target Sum with Dynamic Programming
More Relevant Posts
-
Headline: 🚀 From Confused to Confident: Solving LeetCode 2906! Body: Ever stared at a problem statement and thought, "Where do I even start?" That was me today with LeetCode 2906: Construct Product Matrix. The task seemed simple: For every cell in a matrix, calculate the product of all other elements. But the catch? Doing it efficiently without hitting a Time Limit Exceeded (TLE) error. 💡 The Breakthrough: I realized this is essentially a 2D version of the classic "Product of Array Except Self." Instead of brute-forcing it (which would be O(N²)), I used the Prefix & Suffix Product approach. 🎓 How I visualized it (The Story): Imagine a classroom photo where every student needs to calculate the "score" of everyone else except themselves. 1️⃣ Forward Pass: Calculate the product of everyone standing to your left. 2️⃣ Backward Pass: Calculate the product of everyone standing to your right. 3️⃣ Multiply: Left × Right = Your Answer! By treating the 2D matrix as a continuous stream, I optimized the solution to: ✅ Time Complexity: O(m × n) ✅ Space Complexity: O(1) (excluding output matrix) 🔑 Key Takeaway: Don't rush to code. Spend time visualizing the data flow. Sometimes, breaking a 2D problem into a 1D logic stream makes all the difference. Has anyone else tackled this problem? What was your approach? Let's discuss in the comments! 👇 #LeetCode #DSA #Coding #ProblemSolving #SoftwareEngineering #LearningJourney #Python #Algorithms #TechCommunity
To view or add a comment, sign in
-
-
Non-overlapping Intervals (LeetCode 435) - Medium Today, I tackled a classic interval problem that requires a slightly different strategy. The goal was to find the minimum number of intervals to remove to make the rest non-overlapping. While most interval problems are solved by sorting by start time, this one taught me the power of sorting by end time to make optimal choices. Key Learnings: *Greedy Strategy: To keep as many intervals as possible, it's best to pick the ones that end the earliest. This leaves the maximum possible room for the intervals that follow. *End-Time Sorting: Sorting by end time allows us to always pick the interval that finishes first, which is the 'Greedy' choice for this problem. *Overlap Detection: Once sorted, if a new interval starts before the previously selected one ends, we know it must be removed to avoid a conflict. Complexity: ⏱️ Time Complexity: O(N log N) 📂 Space Complexity: O(1) #LeetCode #CodingJourney #Blind75 #SDEPrep #DataStructures #Python #GreedyAlgorithms #ProblemSolving #TechCareer
To view or add a comment, sign in
-
-
🚀 LeetCode Practice – Another Problem Down Another problem down from the array collection on LeetCode: Remove Element. This one was relatively easy, but it’s all about making consistent progress and staying disciplined with daily practice. 🔎 Problem Overview Given an array nums and a value val, the task is to remove all occurrences of val in-place and return the number of remaining elements. The key constraint is to do this without using extra space, modifying the original array efficiently. 🧠 Approach I used a simple and effective two-pointer technique: • Pointer i scans through the array • Pointer j keeps track of the position to place the next valid element • If the current element is not equal to val, we overwrite at index j and move forward This keeps the solution clean and efficient: • Time Complexity: O(n) • Space Complexity: O(1) ⚙️ Performance • Runtime: 0 ms (Beats 100%) • Memory Usage: 12.51 MB (Beats 12.63%) 💡 Full implementation is available in my featured LeetCode library on my LinkedIn profile—documenting the journey step by step. 📊 Reflection It may be a simpler problem, but this is where discipline, consistency, and momentum are built. Another problem down. Staying consistent. A lot more to come. ❓ Quick question for the community: Do you guys recommend any other approach for this problem, or any optimization I should explore? #LeetCode #Algorithms #Python #CodingJourney #Consistency #Discipline #ProblemSolving
To view or add a comment, sign in
-
🔥 Day 8/100 of My LeetCode Challenge — 0 ms (100%) 🔥 Hook: Most people fail this “easy” problem because they ignore one tiny detail — can you spot it? 💭 Problem: Add 1 to a number represented as an array of digits. Sounds simple, right? But here’s the catch 👇 👉 What if the last digit is 9? 👉 What if ALL digits are 9? Example: [9,9,9] → [1,0,0,0] 💥 🧠 What I learned today: Always think about edge cases Simple problems can hide tricky logic Traversing backwards can simplify carry problems ⚡ My Approach: Start from the end If digit < 9 → add 1 and return If digit == 9 → make it 0 and continue If all become 0 → add 1 at front 💻 Result: ✅ Runtime: 0 ms (100%) ✅ Clean & optimized solution 📈 Consistency Check Day 8 complete. No excuses. No breaks. Small wins daily → Big results later 🚀 #LeetCode #Day8 #CodingJourney #Python #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
✅ Day 73 of 100 Days LeetCode Challenge Problem: 🔹 #3871 – Count Commas in Range II 🔗 https://lnkd.in/gZGbzZ_F Learning Journey: 🔹 Today’s problem asked for the total number of commas used when writing all integers from 1 to n in standard number formatting. 🔹 In this format, a comma appears after every three digits from the right (e.g., 1,000 or 1,000,000). 🔹 Instead of formatting every number individually, I observed that commas start appearing at specific thresholds: • Numbers ≥ 1,000 contribute one comma • Numbers ≥ 1,000,000 contribute two commas • Numbers ≥ 1,000,000,000 contribute three commas, and so on 🔹 I handled each threshold and added the number of integers that contribute commas for that range. Concepts Used: 🔹 Mathematical Pattern Observation 🔹 Conditional Counting 🔹 Large Number Thresholds Key Insight: 🔹 Numbers only start contributing commas after certain digit lengths (powers of 10). 🔹 Counting how many numbers exceed each threshold avoids iterating through all values up to n, making the solution efficient. Complexity: 🔹 Time: O(1) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
✅ Day 87 of 100 Days LeetCode Challenge Problem: 🔹 #2840 – Check if Strings Can be Made Equal With Operations II 🔗 https://lnkd.in/gY73RBb5 Learning Journey: 🔹 Today’s problem extended the previous one, allowing swaps between indices where the difference is even. 🔹 I observed that this again partitions the string into two independent groups: • Even indices (0, 2, 4, …) • Odd indices (1, 3, 5, …) 🔹 I extracted characters from even and odd positions separately for both strings. 🔹 Then, I sorted these groups and compared them between s1 and s2. 🔹 If both even-index groups and odd-index groups match, the strings can be made equal. Concepts Used: 🔹 String Manipulation 🔹 Index Grouping (Parity-based) 🔹 Sorting 🔹 Greedy Observation Key Insight: 🔹 Since swaps are allowed only between indices with even distance, characters can only move within their parity group. 🔹 Therefore, the problem reduces to checking if both parity groups have identical character distributions. Complexity: 🔹 Time: O(n log n) 🔹 Space: O(n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
Day 64 of LeetCode Grind ⚡🔥 Two classic Medium problems today — both are interview must-knows and each teaches a pattern you'll reuse constantly. 1️⃣ Top K Frequent Elements (347) <<< return [x for x, _ in Counter(nums).most_common(k)] >>> * Counter.most_common(k) uses a heap internally to find top-k in O(n log k) — better than sorting which is O(n log n). Want true O(n)? Use Bucket Sort: > Create n+1 buckets indexed by frequency. > Elements with frequency f go into bucket[f]. > Scan buckets from highest frequency down, collect until you have k elements. > Since frequency can't exceed n, bucket index is bounded → pure O(n)! 2️⃣ Product of Array Except Self (238) > No division allowed. O(n). O(1) extra space. Classic prefix + suffix product pattern: * nums = [1, 2, 3, 4] * prefix = [1, 1, 2, 6] ← everything LEFT of i * suffix = [24, 12, 4, 1] ← everything RIGHT of i * result = [24, 12, 8, 6] ← multiply both * Two passes, one output array. The trick is reusing the result array itself — store prefix in the first pass, multiply suffix in-place on the second pass. ✨ Reflection: Both problems follow the same meta-pattern: precompute something so each query is O(1). Whether it's frequency counts or prefix products, the "precompute → combine" mindset is fundamental to efficient algorithm design. #LeetCode #Day64 #Python #PrefixProduct #BucketSort #HashMap #Arrays #Medium #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
✅ Day 74 of 100 Days LeetCode Challenge Problem: 🔹 #653 – Two Sum IV: Input is a BST 🔗 https://lnkd.in/g9vDFKMA Learning Journey: 🔹 Today’s problem required checking whether there exist two nodes in a Binary Search Tree whose values sum to k. 🔹 I performed a Depth-First Search (DFS) traversal using a stack to visit all nodes of the tree. 🔹 While traversing, I stored each node’s value in a list. 🔹 Then I used a hash set to track visited values and checked whether the complement (k - value) already exists. 🔹 If the complement is found, it means two numbers sum to k, so the function returns True. Concepts Used: 🔹 Depth-First Search (DFS) 🔹 Stack-based Tree Traversal 🔹 Hash Set for Fast Lookup 🔹 Two Sum Pattern Key Insight: 🔹 The classic Two Sum approach works well after collecting values from the BST. 🔹 Using a set allows O(1) lookup, making it efficient to check complements during iteration. Complexity: 🔹 Time: O(n) 🔹 Space: O(n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
✅ Day 76 of 100 Days LeetCode Challenge Problem: 🔹 #75 – Sort Colors 🔗 https://lnkd.in/gpH9fEJu Learning Journey: 🔹 Today’s problem required sorting an array containing only 0s, 1s, and 2s (representing colors) in-place without using built-in sort. 🔹 I implemented a selection sort approach, where for each index, I searched for the minimum element in the remaining array. 🔹 Once found, I swapped it with the current position to gradually build the sorted array. 🔹 This ensured the array was sorted in ascending order (0 → 1 → 2). Concepts Used: 🔹 Selection Sort 🔹 In-place Swapping 🔹 Nested Iteration Key Insight: 🔹 Even though the problem has an optimal linear-time solution (Dutch National Flag algorithm), a simple sorting approach like selection sort still works correctly. 🔹 Iteratively placing the smallest remaining element ensures correctness, though not optimal efficiency. Complexity: 🔹 Time: O(n²) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
🚀 LeetCode Win: Missing Number (Beats 100%) Solved this problem using a simple mathematical insight instead of overcomplicating the logic ⚡ 🧠 Core Idea: If a list contains numbers from 0 → n, one number is missing. 👉 So instead of searching for it… I compared: Expected sum (0 → n) Actual sum (given array) ⚙️ Approach: Generate range → 0 to n Compute expected sum Subtract actual array sum ✅ Missing Number = Expected Sum - Actual Sum 🔥 Why this approach stands out: ⏱️ O(n) Time Complexity 💾 O(1) Space Complexity ❌ No extra loops ❌ No sorting ✔️ Clean & efficient 📊 Result: ⚡ Runtime: 0 ms (Beats 100%) 📉 Memory: Optimized 💭 Key Learning: The best solutions aren’t always complex. Sometimes, stepping back and thinking mathematically changes everything. 🚀 Consistency check: Showing up, solving daily, improving 1% 💪 #LeetCode #Algorithms #DataStructures #ProblemSolving #Python #CodingJourney #100DaysOfCode #DeveloperLife #WomenWhoCode #TechGrowth #CodeDaily #ProgrammingLife #SoftwareEngineer #ConsistencyWins
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