🚀 Day 17 of my DSA Journey (LeetCode + Java) Today was all about Prefix Sum, Two-Pass Array Logic, and HashMap-based subarray counting. All three problems helped me think more optimally and understand how preprocessing reduces time complexity. ✅ Problems Solved Today: LC 303 – Range Sum Query: Immutable LC 238 – Product of Array Except Self LC 560 – Subarray Sum Equals K 🧠 My Experience Solving These: 🔸 303. Range Sum Query – Immutable This problem looked simple, but the real trick was understanding how to build logic using a constructor. I learned how prefix sum converts multiple queries into O(1) time. Precomputing prefix sums in the constructor gave me a real-world feel of initialization + efficient querying. 🔸 238. Product of Array Except Self Initially, I solved it in a less optimal way. Then I changed my mindset to the optimal approach: ✔ Left pass → store product before index ✔ Right pass → multiply product after index ✔ No division, no extra space (only result array) After that shift in thinking, the solution became very clean and efficient. 🔸 560. Subarray Sum Equals K This was the most insightful problem of the day. Using a HashMap + prefix sum, I learned how to find subarrays that sum to K in O(n) time: ✔ Maintain cumulative sum ✔ Check if (sum − k) already occurred ✔ If yes → increment count ✔ Store frequencies for later use A beautiful example of how maps help optimize brute-force logic. 📌 Key Takeaway Today: Prefix sums and maps are extremely powerful when combined. With the right preprocessing and logic: O(n²) problems become O(n) Hard problems become intuitive Logic becomes cleaner and more structured Every day, solving new patterns is improving my confidence and problem-solving instincts. 💪 Step-by-step, getting better. On to Day 18! 🚀 #DSA #LeetCode #Java #PrefixSum #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
Day 17 DSA Journey: Prefix Sum & HashMap Optimization
More Relevant Posts
-
🚀 Day 21 of my DSA Journey (LeetCode + Java) Today’s practice focused on Array Manipulation + Counting Frequency problems. All three questions looked simple at first, but each required a deeper thought process to get the most optimized solution. ✅ Problems Solved Today LC 66 – Plus One LC 88 – Merge Sorted Array LC 1189 – Maximum Number of Balloons 🧠 My Experience Solving These: 🔸 66. Plus One This problem was trickier than I expected. Initially, I solved it in a non-optimized way. Then I realized the key insight: Traverse from the end If digit < 9, just increment and return If digit is 9 → make it 0 and continue If all digits are 9 → create new array with leading 1 Once I understood this, I solved it in one single loop—clean and efficient. 🔸 88. Merge Sorted Array My first approach used two loops and sorting, but it was: Extra time Not optimal Then I optimized it by using three pointers: i at the end of arr1 j at the end of arr2 k at the final position Compare & place larger element → move pointers. Finally append remaining elements from arr2. This method was fully optimized (O(n)) without any extra space. 🔸 1189. Maximum Number of Balloons This one was fun! I used a HashMap to count frequency of characters. The tricky part was: How to divide counts correctly for repeated characters like 'l' and 'o' After several dry runs, the logic became clear: Count freq of each char in text Count required freq for word “balloon” Divide actual/required → minimum of all divisions = answer A clean and optimal solution. 📌 Key Takeaway Today Even simple array problems can become tricky if we miss the pattern. Today I reinforced: ✔ Think from the end for digit problems ✔ Use three pointers for merging arrays ✔ Frequency-based problems → always check min(actual/required) ✔ Dry run is your best friend Step-by-step progress every day is building my confidence and logical thinking. 💪 On to Day 22! 🚀 #DSA #LeetCode #Java #Arrays #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
🚀 Day 25 of my DSA Journey (LeetCode + Java) Today’s practice focused on frequency-based problems, using HashMaps, Priority Queues, and simple array traversal. Each question had a different flavor but all were fun to solve! ✅ Problems Solved Today: LC 347 – Top K Frequent Elements LC 451 – Sort Characters by Frequency LC 414 – Third Maximum Number 🧠 My Experience Solving These: 🔸 347. Top K Frequent Elements A classic frequency + heap problem. First, I created a HashMap to count occurrences Then pushed elements into a max-heap/min-heap based on frequency Extracted the top k frequent elements This problem is a great example of how HashMap + PriorityQueue together give an optimal O(n log k) solution. 🔸 451. Sort Characters by Frequency This was a fun problem because it combines strings with frequency sorting. My steps: Count frequency using HashMap Use a max-heap to sort characters by highest frequency Build the final string by repeating each character its number of times Very satisfying to see the string rearranged cleanly based on frequencies. 🔸 414. Third Maximum Number This one was the simplest among the three. I used a single pass approach: Track the largest, second largest, and third largest values Update them as we scan through the array Return the third max or highest max if not enough distinct numbers exist No sorting needed — an O(n) solution with clean logic. 📌 Key Takeaway Today: Frequency-based problems are powerful and appear everywhere. ✔ HashMap is the backbone ✔ PriorityQueue/Heap helps extract top elements ✔ Many problems reduce to counting + ordering ✔ Always aim for O(n log k) or O(n) instead of sorting everything Feeling more confident every day! On to Day 26! 🚀 #DSA #LeetCode #Java #SlidingWindow #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
🚀 Day 22 of my DSA Journey (LeetCode + Java) Today’s practice focused on Strings + HashMap + Character Frequency problems. All three questions required pattern-thinking and careful dry runs to avoid mistakes. ✅ Problems Solved Today: LC 205 – Isomorphic Strings LC 2194 – Cells in a Range on an Excel Sheet LC 383 – Ransom Note 🧠 My Experience Solving These: 🔸 205. Isomorphic Strings This problem looked easy at first, but it got complicated quickly. I first tried using one HashMap, but it failed because: One direction mapping is not enough Characters need to map both ways Then I created two HashMaps: map1 → s → t map2 → t → s With this, all cases passed and the solution became fully optimized. A great learning about bidirectional mapping. 🔸 2194. Cells in a Range on an Excel Sheet Initially, I didn’t understand what the problem was asking. Then I realized: Range is like "K1:L2" Columns vary (letters) Rows vary (numbers) Used a simple nested loop: Outer loop: columns Inner loop: rows Once understood, it became an easy and clean solution. 🔸 383. Ransom Note This problem was tricky because of frequency handling. I used an int[26] array to count characters of the magazine. Count frequency Reduce frequency while checking ransom note If any count < 0 → not possible Dry runs helped me catch mistakes and finalize an O(M + N) optimized solution. 📌 Key Takeaway Today: String problems are all about patterns and frequency logic. ✔ Some problems need two-way mapping ✔ Some require simple range expansion ✔ Many become easy if you use frequency arrays / HashMap ✔ Dry runs remove 90% of mistakes Every day my problem-solving mindset is improving. Consistency is building confidence! 💪 On to Day 23! 🚀 #DSA #LeetCode #Java #HashMap #Strings #CodingJourney #ProblemSolving #Consistency #LearningDaily
To view or add a comment, sign in
-
Day 20/60: Binary Search Trees — The Reality Check 🔍 Today was about implementing Binary Search Trees (BST) in Java. While the concept is simple, the implementation exposed some critical gaps in my recursive logic. The Hurdles & Mistakes: The Return Value Trap: I struggled with returning the correct node during recursion. In Java, if you don't link the returned node back to the parent (root.left = insert(...)), the new node is lost and the tree never grows. Missing Base Cases: I missed a null check on an empty tree, leading to an immediate NullPointerException. In backend development, unhandled nulls are production killers. Duplicate Handling: I didn't initially plan for existing values. Deciding how to handle duplicates is crucial for defining consistent system behavior. The Lessons: Visualize First: I stopped coding and started drawing. If you can’t trace the recursion on paper, you can’t debug it in the IDE. Defensive Coding: I’m learning to write the "Exit Condition" first. Knowing when to stop is more important than knowing how to proceed. State Management: BSTs taught me that how we structure data at the point of entry determines the speed of every future query. Status: ✅ Fixed: Recursive Insertion and Search logic. 🛠️ Working on: Visualizing the call stack deeper. 🎯 Goal: Day 21 – Mastering the three cases of Node Deletion. Refining the logic, one error at a time. 🚀 #JavaDeveloper #Backend #60DaysOfDSA #BinarySearchTree #CodingHurdles #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 29 of my DSA Journey (LeetCode + Java) Today’s focus was on Prefix Sum + Hashing — a powerful combination for solving subarray problems efficiently. Once I understood how prefix sums and hash maps work together, these problems became much clearer and more optimized. ✅ Problems Solved Today: LC 523 – Continuous Subarray Sum LC 325 – Maximum Size Subarray Sum Equals k LC 974 – Subarray Sums Divisible by K 🧠 My Experience Solving These: 🔸 LC 523 – Continuous Subarray Sum This problem was tricky at first. I learned that if two prefix sums have the same remainder when divided by k, the subarray between them is divisible by k. Using a HashMap to store remainder and index helped me solve this in O(n) time. 🔸 LC 325 – Maximum Size Subarray Sum Equals k Here, the goal was to find the longest subarray with sum k. I used prefix sum + HashMap and stored the first occurrence of each sum to maximize subarray length. Simple idea, but very powerful. 🔸 LC 974 – Subarray Sums Divisible by K This problem focused on counting subarrays. Instead of storing indices, I stored frequency of remainders in a HashMap. Each repeated remainder formed valid subarrays divisible by k. 📌 Key Takeaway Today: Prefix Sum + Hashing can solve many subarray problems efficiently. ✔ Convert subarray logic into prefix sums ✔ Use HashMap to track sums or remainders ✔ Handle negative values carefully ✔ One pass → O(n) optimized solutions Every day I’m learning how to recognize patterns faster and write cleaner, optimized code. 💪 On to Day 30 🚀 #DSA #LeetCode #Java #PrefixSum #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
🚀 Day 24 of my DSA Journey (LeetCode + Java) Today’s practice focused on Binary Search + HashSet + Two Pointer — three powerful techniques used across many array problems. Each problem became easier once I recognized the correct pattern. ✅ Problems Solved Today: LC 34 – Find First and Last Position of Element in Sorted Array LC 349 – Intersection of Two Arrays LC 167 – Two Sum II (Input Array Is Sorted) 🧠 My Experience Solving These: 🔸 34. Find First and Last Position of Element in Sorted Array At first it looked tricky, but once I understood the pattern, the solution became clear. I used Binary Search twice: First binary search → find the first occurrence Second binary search → find the last occurrence By adjusting left/right pointers based on comparisons, the problem was solved in O(log n) efficiently. 🔸 349. Intersection of Two Arrays A simple and clean problem using HashSet. Store unique elements of first array in a set Check which elements of second array exist in the set Add them to a result set to maintain uniqueness Then convert the result set to an array. Very straightforward and optimal. 🔸 167. Two Sum II – Input Array Is Sorted This was a classic Two Pointer problem. Use left and right pointers Compare their sum with target Move pointers inward based on sum Since the array was sorted, this approach solved the problem in O(n). 📌 Key Takeaway Today: Choosing the right technique makes problem solving much faster. ✔ Binary Search for finding positions ✔ HashSet for uniqueness and fast lookup ✔ Two Pointers for sorted array problems ✔ Always think about the optimal pattern first Every day I’m improving at recognizing patterns and writing cleaner solutions. On to Day 25! 🚀 #DSA #LeetCode #Java #SlidingWindow #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
Day 11 ( DSA using Java) To strengthen my foundation in Data Structures and Algorithms, I’m committing to solving and sharing LeetCode problem in regular periods of time, along with my thought process and approach. Writing it out helps me learn better and opens the door to meaningful discussion. 🔹 Problem: Q1662 > check if two String Arrays are equivalent 🔹 Core Concept: String , String Functions. solution : public class StringLC { public static boolean arrayStringsAreEqual(String[] word1, String[] word2) { if(String.join("",word1).equals(String.join("",word2))){ return true; } return false; } public static void main(String[] args) { String[] word1 = {"ab","c"}; String[] word2 = {"a","bc"}; System.out.println(arrayStringsAreEqual(word1, word2)); } } I’ve included my solution and time–space complexity analysis. I’d love to hear how others approached this problem—were there alternative or more efficient strategies? Let’s learn, improve, and grow together. #LeetCode #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #LearningInPublic #Java
To view or add a comment, sign in
-
🔥 Day 3 / 100 — NeetCode 150 Challenge 📘 Problems Solved: Two Sum & Group Anagrams (LeetCode) 💻 Language: Java Continuing my 100 Days of Coding journey with NeetCode 150, focusing on hashing patterns, efficient lookups, and grouping techniques. 🔹 Problem 1: Two Sum Brute Force Approach I used a nested loop approach to check all possible pairs. The outer loop starts from index 0. The inner loop starts from i + 1 to avoid duplicate checks. If the sum of both elements equals the target, return their indices. Time Complexity: O(n²) Space Complexity: O(1) Optimized Approach — HashMap I used a HashMap to reduce the lookup time. Store each number as the key and its index as the value. For each element, check if target - nums[i] exists in the map. If found, return the stored index and the current index. Time Complexity: O(n) Space Complexity: O(n) 🔹 Problem 2: Group Anagrams HashMap + Frequency Array Approach I grouped strings by building a character frequency signature for each word. For every string, create an integer array of size 26. Count character frequencies using count[c - 'a']++. Convert the frequency array into a string and use it as the hashmap key. If the key already exists, add the string to the existing list. Otherwise, create a new list and insert it into the map. After processing all strings, return the hashmap values as a list of lists. Time Complexity: O(n · k) (n = number of strings, k = max length of a string) Space Complexity: O(n) ✨ Solving Two Sum and Group Anagrams reinforced how powerful hashing can be for optimizing search and grouping problems. On to Day 4 — building momentum, one problem at a time! 🚀 #100DaysOfCode #NeetCode150 #TwoSum #GroupAnagrams #LeetCode #Java #DSA #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 28 of my DSA Journey (LeetCode + Java) Today’s focus was completely on Sliding Window + Hashing patterns. All three problems looked different, but the core logic was about maintaining a valid window and updating the answer efficiently. ✅ Problems Solved Today: LC 3 – Longest Substring Without Repeating Characters LC 424 – Longest Repeating Character Replacement LC 1004 – Max Consecutive Ones III 🧠 My Experience Solving These: 🔸 3. Longest Substring Without Repeating Characters This is a classic sliding window + HashMap problem. Used a HashMap to store last index of characters If a character repeats, moved left pointer smartly Calculated window length using right - left + 1 Very clean logic once the window movement is clear. 🔸 424. Longest Repeating Character Replacement This one was tricky but powerful. Maintained frequency array for characters Tracked the most frequent character (maxCount) If window size – maxCount > k → shrink window Understanding why maxCount doesn’t decrease was the key insight. 🔸 1004. Max Consecutive Ones III Sliding window on array with condition. Count number of zeros in the window If zeros > k → move left pointer Always track maximum window length Simple idea, very effective solution. 📌 Key Takeaway Today: Sliding Window problems are all about maintaining a valid window. ✔ Decide what makes window invalid ✔ Expand using right pointer ✔ Shrink using left pointer ✔ Update answer at every step ✔ Avoid nested loops → O(n) always wins The more I practice, the faster I recognize patterns. 💪 Consistency + daily effort = confidence. On to Day 29 🚀 #DSA #LeetCode #Java #SlidingWindow #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
Day25 - LeetCode Journey Solved LeetCode 344: Reverse String in Java ✅ This was a simple problem on the surface, but it perfectly highlights how powerful clean logic can be. The goal was to reverse a string in-place using O(1) extra space, which means no extra arrays and no shortcuts. Just pure two-pointer logic. Using the left and right pointers and swapping characters step by step felt very satisfying. It’s one of those patterns that looks small but appears everywhere in interviews and real-world problems. Mastering this makes many string and array problems much easier later on. What I liked about this problem is how it teaches efficiency. Instead of creating new memory, we directly modify the existing array. That mindset of optimizing space is extremely important in DSA. Key takeaways: • Strong practice of the two-pointer technique • In-place operations with constant extra space • Clean and readable swapping logic • Reinforced fundamentals of string manipulation ✅ Accepted successfully ✅ 0 ms runtime with optimal performance Sometimes the simplest problems build the strongest foundations. Consistency with basics is what makes complex problems feel easier later 💪 #LeetCode #DSA #Java #Strings #ProblemSolving #Algorithms #CodingJourney #InterviewPreparation #TwoPointers #Consistency #DailyPractice
To view or add a comment, sign in
-
Explore related topics
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