💡 Day 98 of My DSA Challenge – Longest Subsequence With Limited Sum 🔷 Problem: 2389. Longest Subsequence With Limited Sum 🔷 Goal: For each query, find the maximum number of elements from nums that can form a subsequence with a sum ≤ query value. 🔷 Key Insight: To maximize the subsequence size, we should always pick smaller elements first — this is a greedy choice. Hence, sorting the array ensures we can accumulate the smallest elements until the sum exceeds the query limit. Approach outline: 1️⃣ Sort the array nums. 2️⃣ For each query, add elements one by one until the sum crosses the limit. 3️⃣ Return the count of elements that fit within the limit. This logic can also be optimized further using prefix sums + binary search, but the greedy approach works perfectly within given constraints. 🔷 My Java Approach: Sort the array. Use a helper function to count how many elements fit under the query sum. Store each result in the answer array. 🔷 Complexity: Time → O(n log n + n × m) Space → O(1) Sometimes, simplicity wins. This problem reinforces the power of greedy thinking — starting small, building up gradually, and knowing when to stop. Recognizing such patterns is key to writing clean and intuitive code. 🚀 #100DaysOfCode #Day98 #LeetCode #DSA #Java #ProblemSolving #GreedyAlgorithm #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
Solving Longest Subsequence With Limited Sum using Java and Greedy Algorithm
More Relevant Posts
-
💡 Day 99 of My DSA Challenge – Split Array Largest Sum 🔷 Problem: 410. Split Array Largest Sum 🔷 Goal: Split the array into k non-empty subarrays such that the largest subarray sum is as small as possible. 🔷 Key Insight: This is a classic Binary Search on the Answer problem — the goal isn’t to find a position, but the minimum possible value of the largest subarray sum. Here’s how: The lower bound of our search space is the maximum element in the array (a subarray must at least handle this value). The upper bound is the total sum of the array (one subarray takes all elements). For each mid (possible largest sum), we simulate how many subarrays are needed. If we need more than k, it means our mid is too small → move right. Else, we can try smaller sums → move left. 🔷 My Java Approach: 1️⃣ Define helper isPossible() to simulate how many subarrays form under a max limit. 2️⃣ Apply Binary Search on range [max(nums), sum(nums)]. 3️⃣ Narrow down to the smallest feasible largest sum. 🔷 Complexity: Time → O(n × log(sum(nums))) Space → O(1) This problem is a perfect blend of binary search intuition + greedy validation. It pushes you to think beyond array indices — to apply binary search to ranges of answers instead. Every problem like this sharpens both algorithmic depth and logical structure. 🚀 #100DaysOfCode #Day99 #LeetCode #DSA #Java #ProblemSolving #BinarySearch #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
💡 Day 97 of My DSA Challenge – Single Element in a Sorted Array 🔷 Problem : 540. Single Element in a Sorted Array 🔷 Goal : Find the single element that appears only once in a sorted array where all other elements appear exactly twice, in O(log n) time and O(1) space. 🔷 Key Insight : The array is sorted, and elements appear in pairs — except for one. We can use Binary Search on Indices : Check the mid element and compare it with neighbors. If mid is unique → return it. Otherwise, depending on whether the pair is on the left or right and the parity of the remaining elements, move left or right. This works because the single element shifts the pairing pattern in the array, allowing us to discard half the search space each time. 🔷 My Java Approach : 1️⃣ Binary search over array indices. 2️⃣ Compare mid with neighbors to detect the single element. 3️⃣ Adjust search space using parity logic. 🔷 Complexity : Time → O(log n) Space → O(1) Binary search isn’t just for sorted numbers — it can also be applied to patterns and structural properties in arrays. Recognizing such patterns allows efficient solutions even when the array has special constraints. 🚀 #100DaysOfCode #Day97 #LeetCode #DSA #Java #ProblemSolving #BinarySearch #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
💡 Day 104 of My DSA Challenge – Combinations 🔷 Problem : 77. Combinations 🔷 Goal : Generate all possible combinations of k numbers chosen from the range [1, n]. Example → Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 🔷 Key Insight : This is a backtracking problem — where we explore all possible ways of picking elements while maintaining order and avoiding repetition. The core difference from permutations is that the order of elements doesn’t matter — [1,2] and [2,1] are the same combination. 🔷 Approach : 1️⃣ Start from the first number (idx = 1). 2️⃣ At each step, decide whether to include the current number in the combination or skip it. 3️⃣ Recursively build combinations until the list size reaches k. 4️⃣ Backtrack to explore other possibilities. 🔷 My Java Approach : Used recursion to explore all inclusion/exclusion choices. Added combinations when list size equals k. Backtracked after each recursive call to maintain correct state. 🔷 Complexity : Time → O(C(n, k)) Space → O(k) (for recursion and temporary list) This problem strengthens understanding of decision trees and combinatorial logic, which form the backbone of many recursive and dynamic programming patterns. Every problem adds a new layer to logical thinking — today, it was about choosing without caring about order, but caring deeply about structure. #Day104 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Backtracking #Recursion #Combinations #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #EngineerMindset #DeveloperJourney #GrowthMindset #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
🚀 Day 58 of My LeetCode Journey 🚀 🔹 Problem: Search Insert Position 🔹 Topic: Binary Search (Fundamental DSA Technique) Today’s challenge focused on enhancing one core skill: thinking in terms of boundaries and decisions. The task was simple — in a sorted array, find the index of the target element. If it doesn’t exist, return the index where it logically should be inserted. What made this problem interesting is that instead of searching linearly, we leverage Binary Search, which reduces the operations drastically. ✅ Key Takeaways & Learning: Binary Search is not just used to find something — it can also determine the correct position for insertion. Understanding how low, mid, and high move helps build clear logic flow. The index where the search ends (low) gives the correct insert position, even if the element doesn't exist. Rewriting brute-force logic into binary search trains the brain to think in terms of optimization. ⏱️ Complexity Analysis: MetricValueTimeO(log n)SpaceO(1) 🌱 Personal Reflection: Every binary search problem improves clarity of thought. From checking a value to identifying a boundary or insert point — the mindset shifts from “finding an element” to “solving a pattern.” #100DaysOfCode #LeetCode #DSA #BinarySearch #Java #ProblemSolving #LearningInPublic #TechJourney #ConsistencyIsKey
To view or add a comment, sign in
-
-
I’ve realized that DSA is not just about solving problems—it’s about how many you solve and how deeply you understand the underlying concepts. The more problems you practice, the easier it becomes to recognize patterns and apply the right approach. Today, I worked on LeetCode 1971 – Find if Path Exists in a Graph, marked as an Easy problem. But to solve it confidently, you actually need strong fundamentals in: 🔹 Graph theory 🔹 DFS & BFS (and when to use which) 🔹 Difference between Graphs vs Trees 🔹 Edge List vs Adjacency List 🔹 How to build an adjacency list in code 🔹 How DFS works internally on graphs After around two months of consistent practice, I’m finally able to identify the prerequisites required for each problem and approach them with a structured mindset. If you're exploring graphs, I highly recommend giving this problem a try. Here’s the problem: https://lnkd.in/g6hMyn88 And here’s my LeetCode profile if you'd like to connect or share feedback: https://lnkd.in/gp38YMN7 #LeetCode #DSA #Java #SoftwareEngineering #Graphs #Coding #LearningJourney
To view or add a comment, sign in
-
-
🔥 Day 107 of My DSA Challenge – Combination Sum II 🔷 Problem : 40. Combination Sum II 🔷 Goal : Find all unique combinations of numbers from a given list that sum up to a target. Each number can be used only once, and duplicate combinations are not allowed. 🔷 Key Insight : This is a backtracking + deduplication problem. The challenge is not just summing numbers—it’s ensuring uniqueness and exploring all valid combinations efficiently. 🔷 Approach : 1️⃣ Sort the candidates to handle duplicates easily. 2️⃣ Recursively pick each number and reduce the target. 3️⃣ If the target hits zero, record the combination. 4️⃣ Backtrack to explore other possibilities. 5️⃣ Skip duplicates to avoid repeating combinations. 🔷 Complexity : Time: O(2^N) — exploring all subsets Space: O(N) — recursion stack and temporary list Backtracking teaches precision, patience, and logical thinking—every branch you explore is a test of careful reasoning. #Day107 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Backtracking #Recursion #CombinationSum #CodingChallenge #Algorithms #DataStructures #DeveloperJourney #Growth #Programming #SoftwareEngineering #CodeDaily #TechJourney #EngineerMindset #CodeLearning #CompetitiveProgramming #LogicBuilding #CareerInTech
To view or add a comment, sign in
-
-
🚀 Day 22 of #GFG160DaysDSAChallenge Today I tackled the H-Index problem (LeetCode 274 / GFG), a classic medium-level problem that tests understanding of arrays, counting, and problem optimization. 💡 Problem Statement: Given an array citations[] representing the number of citations each paper has, compute the H-Index — the maximum h such that the researcher has at least h papers with ≥ h citations. 🔑 My Approach: Brute Force: Check every possible h from 0 → n and count papers with citations ≥ h → O(n²). Better (Sort-based): Sort citations and iterate to find the first index where citations[i] ≥ n - i → O(n log n). Optimal (Counting/Bucket): Create a bucket array to count how many papers have 0…n citations. Iterate from high to low to accumulate papers with ≥ h citations. Return the largest h that satisfies the condition → O(n) ✅ 💡 Key Takeaways: Often, sorting isn’t needed — sometimes just counting frequencies is enough. The problem is a great example of thinking “better → optimal” by exploiting constraints (h ≤ n). Understanding how to aggregate information instead of iterating repeatedly is a big step in DSA. #DSA #100DaysOfCode #GFG160Days #Java #CodingChallenge #LeetCode #ProblemSolving #HIndex
To view or add a comment, sign in
-
-
✨ Day 103 of My DSA Challenge – Permutations 🔷 Problem : 46. Permutations 🔷 Goal : Generate all possible orderings (permutations) of a given array of distinct integers. Example → Input: [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 🔷 Key Insight : This problem is a classic recursion and backtracking pattern — exploring all possible arrangements by making choices and undoing them. Here’s how I approached it : 1️⃣ Recursion (Depth-First Search): Build each permutation step by step. 2️⃣ Visited Array: Track which elements have been used so far. 3️⃣ Backtracking: After exploring a path, undo the choice (remove the last element and mark it unvisited). Every recursive call expands the decision tree until all positions are filled, ensuring every unique ordering is generated. 🔷 My Java Approach : Recursive helper() function generates all permutations. Base case → when current list size equals array length. Used a boolean[] vis to manage state efficiently 🔷 Complexity : Time → O(n × n!) (since there are n! permutations and copying each list takes O(n)) Space → O(n) (for recursion and visited tracking) This problem beautifully tests recursion fundamentals, state management, and the art of backtracking — essential tools for mastering combinatorial problems. Each problem reminds me that problem-solving is less about memorizing patterns and more about learning how to think. #Day103 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Recursion #Backtracking #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
🌟 Day 44 – LeetCode Practice Problem: Product of Array Except Self (LeetCode #238) 📌 Concept: Given an integer array, create a new array where each element equals the product of all other elements except itself, without using division. 🧠 My Approach: First pass → compute prefix products (multiply everything before current index) Second pass → compute suffix products (multiply everything after current index) Combine both to get the result for each index efficiently No extra multiplication array used — optimized and clean logic ⚡ This avoids division and runs in linear time — exactly what the problem demands ✅ 📈 Result: ✅ Accepted ⚡ Runtime: 2 ms (Beats ~87%) 📦 Memory: Efficient usage 💡 Key Learning: This problem reinforces the power of prefix & suffix computation — a common trick in array manipulation + interview favorite. Great way to improve problem-solving without relying on brute force or division. --- 🚀 Growing stronger every day in DSA! #LeetCode #DSA #Java #ProblemSolving #PrefixSuffix #CodingJourney #ArrayProblems #LearningMindset
To view or add a comment, sign in
-
-
✨ Day 101 of My DSA Challenge – Magnetic Force Between Two Balls 🔷 Problem: 1552. Magnetic Force Between Two Balls 🔷 Goal: Place m balls into sorted basket positions such that the minimum magnetic force (i.e., minimum distance between any two balls) is as large as possible. 🔷 Key Insight: This is another brilliant Binary Search on the Answer problem. Instead of directly computing distances, we binary search for the maximum possible minimum distance that still allows placing all balls. Here’s how the logic works: 1️⃣ Sort all basket positions. 2️⃣ Use binary search on the range of possible distances (0 to max(position) - min(position)). 3️⃣ For each middle distance mid, check feasibility using a greedy approach — place balls while maintaining at least mid distance apart. 4️⃣ If it’s possible → try a larger distance. If not → reduce the distance. 🔷 My Java Approach: Implemented a helper function isPossible() to check if we can place all balls for a given minimum distance. Used Binary Search to maximize that minimum distance. 🔷 Complexity: Time → O(n × log(maxDist)) Space → O(1) This problem beautifully blends sorting, binary search, and greedy placement — showing how abstract concepts like “searching on the answer” translate into real algorithmic reasoning. Every new day strengthens my foundation in Binary Search patterns, sharpening both logic and implementation clarity. 🚀 #Day101 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #BinarySearch #GreedyAlgorithm #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #LearnToCode #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
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