🚀 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
Day 24 of DSA Journey: Binary Search, HashSet, Two Pointer Techniques
More Relevant Posts
-
🚀 Day 26 of my DSA Journey (LeetCode + Java) Today’s practice covered Stack, Two-Pointer string processing, and Prefix matching. Each problem had a different pattern, so it was a great mixed-learning day! ✅ Problems Solved Today: LC 20 – Valid Parentheses LC 443 – String Compression LC 14 – Longest Common Prefix 🧠 My Experience Solving These: 🔸 20. Valid Parentheses This is a classic stack-based validation problem. My steps: Push opening brackets into stack When closing bracket appears, check top of stack If matching pair → pop Else → return false Finally, if stack is empty → parentheses are valid. A very clean and logical stack problem. 🔸 443. String Compression This problem was interesting because it relies on two-pointer string traversal. Here’s how I solved it: Use one pointer to scan the string Count how many times a character repeats Write the character + its count into the main array Maintain a separate write index It’s an optimized in-place solution, and understanding the pointer movement is the key. 🔸 14. Longest Common Prefix A very popular string problem. My approach: Take the first string as the initial prefix Compare it with every next string Trim the prefix whenever mismatch occurs Continue until the shortest valid prefix remains Simple logic but very important technique for prefix-matching problems. 📌 Key Takeaway Today: Working on mixed patterns like Stack, String Compression, and Prefix Matching helps build versatility. ✔ Stack is perfect for matching pairs ✔ Two-pointer technique makes string processing efficient ✔ Prefix trimming is a powerful string strategy Every day I’m building stronger intuition toward string and stack problems. On to Day 27! 🚀 #DSA #LeetCode #Java #SlidingWindow #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
🚀 A tiny mistake. A big lesson in Java. Recently while debugging a DSA solution, I ran into this condition: while(nums1[p1] == res[i-1] && p1 < n1) Looks perfectly fine at first glance, right? But Java evaluates left to right. So what actually happens is: nums1[p1] == res[i-1] // evaluated FIRST And only after that: p1 < n1 If p1 == n1, the code tries to access nums1[n1] → 💥 ArrayIndexOutOfBoundsException The fix? Just change the order: while(p1 < n1 && nums1[p1] == res[i-1]) Now bounds are checked before access. Safe. Correct. Stable. 🧠 Real lesson here: This wasn’t about syntax. This wasn’t about logic. This was about execution order. Small details in code structure can break entire algorithms. 💡 Takeaways: • Code is not just about what you write • It’s about how the compiler reads it • Order of conditions matters • Evaluation order matters • Safety checks must always come first • Clean logic must also be safe logic This one bug reminded me that: Great code isn’t just correct — it’s defensively written. The difference between a good developer and a strong developer is often attention to tiny details like these. Because in real systems, small mistakes don’t fail small — they fail big. #Java #DSA #Debugging #ProblemSolving #CleanCode #ProgrammingLessons #SoftwareEngineering #LearningByDoing #DeveloperLife #GrowthMindset
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 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
-
🧠 “He tried to learn DSA using Java…” …and suddenly everything started timing out 😅 Same logic in C++? Runs smoothly. This literally happened to me recently. I was solving a DSA problem: ✔ Same algorithm ✔ Same complexity ✔ Same approach Java → TLE C++ → Works fine At first, it feels frustrating. But then you realize — there’s a deeper lesson here. 💡 Why does this happen? It’s NOT because Java is bad. It’s because performance is affected by language internals and runtime behavior, especially when problems are tight on limits. Some key reasons: 1️⃣ Input / Output speed Java’s default I/O is slow unless you explicitly optimize it. 2️⃣ Object overhead & Garbage Collection Java creates objects aggressively and has GC pauses. C++ gives more direct memory control. 3️⃣ Constant factors matter Even with the same O(N log N) complexity, Java can be noticeably slower due to: JVM abstraction Bounds checking Method call overhead ⚠️ Reality check: Java often needs ✅ Faster IO ✅ Iterative DFS instead of recursion ✅ Custom fast input classes ✅ Micro-optimizations Just to survive. Note: Java is sufficient for almost all DSA problems. In some tight cases, it just needs extra boilerplate like faster I/O or small optimizations. The core logic and algorithm still matter the most. #DSA #Java #Cpp #Programming #ProblemSolving #SoftwareEngineering #CodingLife #LearnToCode #TechCommunity
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
-
-
🚀 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
-
📌 DSA Series — Day 4 | Problem 1 | Arrays Problem: Longest Subarray with Given Sum K (Positive Integers) 🔹 Problem Understanding: Given an array of positive integers and an integer K, find the length of the longest subarray whose sum is exactly K. 🔹 Approach (Sliding Window): Use two pointers (left and right) to represent a window. Expand the window by moving right and adding elements to the sum. Shrink the window from the left whenever the sum exceeds K. Update the maximum length when the window sum equals K. 🔹 Why this works: Since all elements are positive, increasing the window always increases the sum and shrinking it always decreases the sum. This monotonic behavior makes the sliding window approach valid and optimal. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(1) 🔹 Java Implementation: class Solution { public int longestSubarray(int[] arr, int k) { int left = 0, sum = 0, maxLen = 0; for (int right = 0; right < arr.length; right++) { sum += arr[right]; while (sum > k) { sum -= arr[left++]; } if (sum == k) { maxLen = Math.max(maxLen, right - left + 1); } } return maxLen; } } 🔹 Key Insight: This approach fails when negative numbers are present. 📈 Continuing my structured DSA problem-solving series. #DSA #Arrays #Java #SlidingWindow #ProblemSolving #StriversA2Z #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 34 of mastering DSA patterns in Java Today’s problem looked like a simple binary array question… but it actually used a powerful Prefix Sum + HashMap pattern. 🧠 Pattern: Prefix Sum with Difference Tracking 🔹 Problem solved: • LeetCode 525 – Contiguous Array https://lnkd.in/dQbitxSZ 💡 Key insight: To find the longest subarray with equal 0s and 1s, we track the difference between count of 0s and 1s while traversing. If the same difference appears again, it means the elements in between have equal numbers of 0 and 1. This turns a brute-force O(n²) idea into an efficient O(n) solution. 🛠 Implementation idea: Traverse once, maintain counts of 0s and 1s, compute their difference, and store the first index of each difference in a HashMap to calculate maximum length instantly. 📌 Why use this pattern? To convert balance or equality conditions into a prefix sum difference problem. 📍 Where is it used? Equal 0-1 subarrays, balanced segments, cumulative comparisons, and many interview-level array problems. ⚙️ How to recognize it? If a question asks for: • equal count of two values • longest balanced subarray • continuous segment with equality condition → Think Prefix Sum + HashMap on differences. 🙏 Grateful to my mentor @PratyushNarain for guiding me to see the pattern behind the problem, not just the solution. 📚 Big lesson of the day: When you understand how to transform problems into prefix sums, many medium questions become much easier to solve. Have you solved any balanced subarray problems recently? 👇 #DSA #Java #PrefixSum #HashMap #ProblemSolving #100DaysOfCode #LearningInPublic #DSA #KadanesAlgorithm #DynamicProgramming #ProblemSolving #DataStructures #Algorithms #CodingJourney #LeetCode #LearningInPublic #BTechCSE #SoftwareEngineering #PlacementsPrep #CodingPractice #TechCareer #Consistency
To view or add a comment, sign in
-
-
Day22 - LeetCode Journey Solved LeetCode 242: Valid Anagram in Java ✅ This problem was a nice reminder of how simple ideas can lead to clean and effective solutions. Checking whether two strings are anagrams really comes down to understanding character frequency and order. By sorting both strings and comparing them character by character, the logic becomes very straightforward and easy to follow. What I liked about this problem is how it strengthens fundamentals of string handling and arrays. It also shows how preprocessing data can simplify the main comparison logic. Small steps like converting strings to character arrays and sorting them make the solution both readable and reliable. Key takeaways: • Better understanding of string to array conversion • Using sorting as a tool to simplify comparisons • Writing clean and minimal logic • Strengthening basics of string manipulation ✅ All test cases passed successfully ✅ Logic kept simple and efficient ✅ Another step forward in building strong DSA foundations Consistency with such problems really builds confidence over time 💪 #LeetCode #Java #DSA #Strings #ValidAnagram #ProblemSolving #CodingJourney #InterviewPreparation #Algorithms #Consistency #LearningEveryday
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