Day 11/90 DSA Journey Today I implemented an efficient solution for the classic DSA problem “Subarray Sum Equals K” using Prefix Sum + HashMap. -> Approach: Maintain a running prefix sum while traversing the array. Use a HashMap to store the frequency of prefix sums. At each index, check if (currentSum - k) exists in the map. If it exists, it means there is a subarray ending at the current index with sum = k. -> Key Insight: If sum[j] - sum[i] = k, then the subarray (i+1 to j) has sum k. -> Code Highlights: Initialize map.put(0,1) to handle edge cases. Continuously update frequency of prefix sums. Efficient lookup using HashMap. -> Time Complexity: -> O(n) — We traverse the array only once. -> Space Complexity: -> O(n) — In the worst case, we store all prefix sums in the HashMap. -> Why this is powerful? This approach avoids nested loops (O(n²)) and optimizes the solution using hashing. #DSA #Java #LeetCode #Coding #Hashing #PrefixSum #ProblemSolving
Efficient Subarray Sum Equals K Solution with Prefix Sum + HashMap
More Relevant Posts
-
🚀 DSA Journey Update: 7/75 Solved another problem today: Product of Array Except Self 💡 Key Idea: Used prefix (left) and suffix (right) products to build the answer without using division and in O(n) time. 🔍 Example: Input: [1,2,3,4] Output: [24,12,8,6] ⚡ Learning: Optimized approach using two passes Space optimization by reusing the same array Stronger understanding of prefix/suffix patterns Step by step progress… consistency matters more than speed 🔥 #DSA #Java #LeetCode #CodingJourney #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 123/360 🚀 📌 Topic: Recursion 🧩 Problem: Generate Parentheses Problem Statement: Given n pairs of parentheses, generate all combinations of well-formed (valid) parentheses. 🔍 Example: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] 💡 Approach: Backtracking 1️⃣ Step 1 – Start with an empty string and track open (oc) and close (cc) brackets 2️⃣ Step 2 – Add "(" if oc < n (we still have opening brackets left) 3️⃣ Step 3 – Add ")" only if cc < oc (to maintain valid structure) 👉 This ensures we only generate valid combinations (no extra filtering needed) ⏱ Complexity: Time: O(2ⁿ) (Catalan growth) Space: O(n) recursion stack 📚 Key Learning: Backtracking works best when we avoid invalid choices early, instead of fixing them later. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #123DaysOfCode #LeetCode #Backtracking
To view or add a comment, sign in
-
-
💻 Day 80 – DSA Practice (Binary Trees) Today’s challenge: 👉 Find all root-to-leaf paths where the sum equals a given target. 🔹 Approach: Use Depth-First Search (DFS) Track the current path and remaining sum When reaching a leaf node, check if the sum matches 💡 Key Concepts: Recursion + Backtracking Tree traversal (DFS) Efficient sum handling ⚡ Insight: Reducing the target sum at each step makes the solution cleaner and avoids recalculating sums. #DSA #BinaryTree #Java #CodingJourney #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🚀Solved Validate Stack Sequences by simulating the stack using a simple array instead of relying on built-in stack classes. This helped reduce overhead and kept the operations efficient. Focused on writing clean logic with optimal time complexity. 😊 Result: 💯 Achieved 0 ms runtime beating 100% of submissions, with memory usage around 45.52 MB performing in the top percentile. 💥 #LeetCode #DSA #Java #Coding #ProblemSolving #Preparation #Anurag_University 🚀🚀
To view or add a comment, sign in
-
-
🔥 Day 58 of DSA Journey Solved the classic 3Sum (LeetCode 15) problem today. 💡 Key Learnings: Sorting simplifies the problem structure Fix one element and apply the two-pointer approach Handling duplicates correctly is crucial to avoid redundant results ⏱️ Complexity: Time: O(n²) Space: O(1) (excluding output) 📊 Result: Runtime: 33 ms (Beats 73.75%) Strengthened understanding of two-pointer pattern This problem reinforced an important pattern: 👉 Reduce 3Sum → 2Sum using two pointers On to the next challenge 🚀 #DSA #LeetCode #CodingJourney #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
😎 Day 39 of Solving dsa -->longest consecutive sequence. 🚀 Approach First, add all elements of the input array nums into a hash set for efficient O(1) lookups. Initialize a variable longest_streak to 0. Iterate through the array nums again. For each number num: Check if num - 1 exists in the hash set. If it does, num is part of a longer sequence that will be processed later, so we skip it. If num - 1 does not exist in the hash set, num is the start of a consecutive sequence. Start a nested loop from num, incrementing by one, and check if each subsequent number exists in the set. Count the length of this sequence. Update longest_streak with the maximum length found so far. Return longest_streak. 📈 Complexity Time complexity: O(n) — Although there is a nested loop, each element in the hash set is visited at most twice: once during insertion and once during a streak check. Space complexity: O(n) — We store all n elements in the hash set. #programming #solving #java #dsa #100 days challenge #logic #leetcode #striversheeet #tuf #daily challenge
To view or add a comment, sign in
-
-
DSA Day 20 – Frequency Counting with Strings Today I solved the “Ransom Note” problem on LeetCode. Problem: Check whether the ransomNote string can be constructed using letters from the magazine string, where each letter can be used only once. Approach Used: -> Counted frequency of characters in ransomNote -> Counted frequency of characters in magazine -> Compared required characters with available characters -> If any required count was greater than available count → false Time Complexity: -> O(n + m) Space Complexity: -> O(1) (Only lowercase English letters / limited character set) Key Learning: -> Frequency counting works not only for arrays, but also for strings -> HashMap helps compare required vs available resources efficiently -> Always check constraints, because they can reduce space complexity What I Realized: Many string problems are actually counting problems in disguise. The better you recognize patterns, the faster you solve problems. Thanks to Pulkit Aggarwal sir for guiding me in DSA and helping me understand problem-solving patterns. Consistency continues, one problem every day. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
#CodeEveryday — My DSA Journey | Day 3 🧩 Problem Solved: Combination Sum III (LeetCode #216) 💭 What I Learned: Used backtracking to find all possible combinations of k numbers (1–9) that sum up to a target n. At each step: ✔️ Decided whether to include the current number ✔️ Reduced both the remaining sum (n) and count (k) ✔️ Ensured each number is used only once by moving to the previous index Applied constraints effectively to prune recursion when: Remaining sum becomes negative Required count becomes invalid This improved my understanding of handling multiple constraints (sum + size) simultaneously in recursion. ⏱ Time Complexity: O(C(9,k) 🧠 Space Complexity: O(k) (recursion depth) ⚡ Key Takeaways: ✔️ Backtracking with multiple constraints requires careful pruning ✔️ Fixed input size can significantly reduce complexity ✔️ Choosing + skipping pattern helps explore all valid combinations 💻 Language Used: Java ☕ 📘 Concepts: Backtracking · Recursion · Combinations · Constraint Handling #CodeEveryday #DSA #LeetCode #Java #Backtracking #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
=> Day 20/90 DSA Journey Solved: Count Odd Numbers in an Interval (LeetCode 1523) Instead of using loops, I applied a simple mathematical formula to achieve an O(1) solution. 🔹 Key Idea: Count of odd numbers between low and high can be calculated directly using: -> ((high + 1) / 2) - (low / 2) 🔹 Why this works: -> It efficiently counts odds up to high and subtracts odds before low. 🔹 Example: Input: low = 3, high = 7 Output: 3 (Odd numbers → 3, 5, 7) -> Time Complexity: O(1) -> Space Complexity: O(1) #Java #DSA #LeetCode #ProblemSolving #Coding #Optimization
To view or add a comment, sign in
-
-
=>Day 17/90 DSA Journey Solved: Continuous Subarray Sum (LeetCode) Today I worked on an interesting problem involving Prefix Sum + HashMap, which helped me optimize from a brute-force O(n²) solution to an efficient O(n) approach. If the same remainder (sum % k) appears again, it means the subarray between those indices has a sum divisible by k. -> What I learned: How to use prefix sum effectively Importance of storing remainders in HashMap Handling edge cases like subarray length ≥ 2 ->Optimization: Brute Force → O(n²) ❌ Optimized Approach → O(n) ✅ #LeetCode #DSA #Java #Coding #ProblemSolving #100DaysOfCode
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