Problem Solved: Super Reduced String (Stack Approach) Today I solved an interesting string problem where we repeatedly remove adjacent matching characters until no more reductions are possible. 💡 Key Idea: Used a StringBuilder as a stack to efficiently remove adjacent duplicates in a single pass. 🔧 Tech Used: Java | String Manipulation | Stack Concept 📌 What I Learned: How stack-based thinking simplifies string problems Writing optimized O(n) solutions Clean handling of edge cases like empty string 📊 Example: Input: aaabccddd Output: abd This problem is a great example of how simple logic + the right data structure can lead to efficient solutions. #Java #DataStructures #CodingPractice #ProblemSolving #Algorithms
Solving String Reduction with Stack Approach in Java
More Relevant Posts
-
Day 18 of my #30DayCodeChallenge: The Art of String Manipulation! The Problem: Count and Say. A classic string problem where each term is generated by describing the previous term using Run-Length Encoding (RLE). The Logic: The key here is to simulate the process of "reading out loud" what you see. Using a StringBuilder and a two-pointer approach, we can efficiently build the next string in the sequence: 1. Iterative Progression: Starting from the base case "1", we loop n - 1 times to reach the n" term. 2. The Two-Pointer Scan: For each string, I used an inner whi le loop to find groups of identical consecutive characters. 3. Count and Append: * Count: Calculate the length of the run (number of times a digit repeats). *Say: Append the count followed by the digit itself to our StringBuilder. 4. Update & Repeat: The newly built string becomes the input for the next iteration. This problem is a great exercise in managing indices and understanding how strings are constructed dynamically in Java. One step closer to mastery. Onward to Day 19! #Java #Algorithms #DataStructures #LeetCode #ProblemSolving #150DaysOfCode #SoftwareEngineering #CodingLife #Strings
To view or add a comment, sign in
-
-
🚀 LeetCode Problem of the Day 📌 Problem: Minimum Distance to Target Element Given an integer array nums (0-indexed) and two integers target and start, we need to find an index i such that: nums[i] == target |i - start| is minimized 👉 Return the minimum absolute distance. 💡 Key Idea: We simply scan the array and track the minimum distance whenever we find the target. 🧠 Approach Traverse the array Whenever nums[i] == target, compute abs(i - start) Keep updating the minimum result 💻 Java Solution class Solution { public int getMinDistance(int[] nums, int target, int start) { int res = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { res = Math.min(res, Math.abs(i - start)); } } return res; } } 📊 Complexity Analysis ⏱ Time Complexity: O(n) → single pass through the array 🧠 Space Complexity: O(1) → no extra space used ⚡ Simple linear scan, optimal solution — sometimes brute force is already the best solution! #LeetCode #Coding #Java #ProblemSolving #DataStructures #Algorithms #InterviewPrep
To view or add a comment, sign in
-
-
Day 35 of Consistency 💻🔥 Solved Longest Substring Without Repeating Characters — a classic sliding window problem that really tests optimization skills. ✨ Key Takeaways: Mastered the sliding window technique Used HashMap for efficient lookup Improved understanding of two-pointer approach ⚡ Performance: Runtime: 5 ms Beat: 87%+ submissions Every day is about getting sharper, not just solving problems. #LeetCode #DataStructures #Algorithms #CodingJourney #Consistency #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 27 of #100DaysOfCode Solved Single Element in a Sorted Array 🔍 Today’s problem was a great mix of binary search + pattern observation. Instead of checking every element, I used index parity (even/odd) to eliminate half of the search space each time — achieving O(log n) time complexity ⚡ 🔍 Key Learnings: How sorted structure helps optimize search Using index parity to detect the correct half Writing clean edge-case handling for boundaries 💻 Implemented in Java with optimal approach 📈 Runtime: 0 ms | Beat 100% #DSAwithEdSlash #LeetCode #BinarySearch #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 31 of #100DaysOfCode Solved Find Target Indices After Sorting Array 🔍 Today’s problem looked like a sorting question, but the real trick was avoiding sorting altogether 😏 💡 Key Insight: Count elements less than target → starting index Count elements equal to target → number of indices ⚡ No sorting needed → O(n) time, O(1) space 🔍 Learned: Optimize before you implement brute force Counting can replace sorting in many cases Cleaner logic = faster code 💻 Implemented in Java #DSAwithEdSlash #LeetCode #Java #ProblemSolving #100DaysOfCode @edslash
To view or add a comment, sign in
-
-
Day 97/200 – LeetCode Challenge Solved “Largest Rectangle in Histogram” (Hard) today. This problem is a great example of how powerful the Monotonic Stack technique can be. Instead of brute force, we efficiently determine how far each bar can extend to compute the maximum rectangle area. Using a monotonic increasing stack to track indices. Identifying left and right boundaries for each bar. Every day is making data structures feel more intuitive! #Day96 #LeetCode #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 32 of #100DaysOfCode Solved LeetCode 179 – Largest Number 🔢 Today’s problem was a great reminder that sorting isn’t always straightforward. Instead of normal numeric sorting, the trick is to compare numbers based on their string concatenation order. 💡 Key Insight: To decide order between two numbers a and b, compare: ab vs ba Whichever forms the larger number should come first. 🔍 What I learned: Custom sorting using comparators Converting integers to strings for flexible comparison Edge case handling (like leading zeros → return "0") ⚡ Approach: Convert integers to strings Sort using (b+a).compareTo(a+b) logic Build the final result using StringBuilder 💻 Efficient and clean solution with strong real-world relevance in greedy + sorting problems #100DaysOfCode #DSA #LeetCode #Java #CodingJourney #ProblemSolving #Algorithms #DSAwithEdSlash @edslash
To view or add a comment, sign in
-
-
🚀 09/04/26 — Alternating Precision: Mastering String Merging Today I tackled Merge Strings Alternately (LeetCode 1768), focusing on efficient string construction and pointer management. This problem is an excellent exercise in handling sequences of different lengths using a unified traversal strategy. 🧵 Merge Strings Alternately Logic The goal is to merge two strings by adding letters in alternating order, starting with the first string. Any remaining letters from the longer string are appended to the end. StringBuilder Strategy: I used StringBuilder for the result to ensure efficient appends, avoiding the overhead of string concatenation in Java. The Interleaved Loop: I initialized two pointers, i and j, at 0. A single while loop runs as long as either string has remaining characters (i < word1.length() || j < word2.length()). Conditional Appending: Inside the loop, I check each pointer individually. If a pointer is still within its string's bounds, I append the character and increment that pointer. Automatic Handling: This structure naturally handles cases where one string is longer, as the conditions safely skip the shorter string once it is exhausted. Complexity Metrics: Time Complexity: O(a + b), where a and b are the lengths of word1 and word2, as every character is visited once. Space Complexity: O(a + b) to store the merged result in the StringBuilder. 📈 Consistency Report Today’s session further solidifies the pointer-based intuition I've been developing. The logic used here—managing multiple indices within a single loop—mirrors the "Two Sum" and "String Search" patterns I mastered earlier in the roadmap. Achieving a 95.66% beat rate proves that choosing the right tools, like StringBuilder, is just as important as the algorithm itself. My 1ms alternating merge implementation is attached below! 📄👇 #DSA #Java #LeetCode #StringManipulation #TwoPointers #Complexity #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
📅 Date: April 27, 2026 Day 6 of my LeetCode Journey 🚀 ✅ Problem Solved: 14. Longest Common Prefix 🧠 Approach & Smart Solution: To solve this problem, I used a highly efficient Horizontal Scanning technique. Instead of comparing characters index by index across all strings, I assumed the very first string was the common prefix. Then, I iteratively compared it with the next strings, shaving off characters from the end until a match was found. By leveraging Java's built-in startsWith() method, the logic is kept clean and readable! • Pseudo-code: Assume the first string in the array is the initial 'prefix'. Loop through the rest of the strings in the array: While the current string does not start with the 'prefix': Shorten the 'prefix' by removing its last character. If the 'prefix' becomes completely empty, return "" (no common prefix exists). Return the final 'prefix' after checking all strings. This step-by-step reduction ensures we only do as much work as absolutely necessary. ⏱️ Time Complexity: O(S) (where S is the sum of all characters in all strings) 📦 Space Complexity: O(1) (Only modifying the prefix string, no extra arrays used) 📊 Progress Update: • Streak: 5 Days 🔥 • Difficulty: Easy • Pattern: String / Horizontal Scanning 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Smartly utilizing built-in string methods like startsWith and substring can drastically reduce code complexity! 💡 #LeetCode #DSA #Strings #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
💡 Day 63 of LeetCode Problem Solved! 🔧 🌟 796. Rotate String 🌟 🔗 Solution Code: https://lnkd.in/dbS6k9gb 🧠 Approach: • Checked if both strings have equal length — if not, instantly return false. • Concatenated s with itself → all possible rotations of s are embedded inside s + s. • Used Java's built-in contains() to check if goal is a substring of the doubled string. ⚡ Key Learning: • A clever observation can replace brute-force rotation simulation entirely. Doubling the string is a go-to trick for rotation problems — simple, elegant, and highly effective. ⏱️ Complexity: • Time: O(N) • Space: O(N) #LeetCode #Java #DSA #ProblemSolving #Consistency #CodingJourney #Algorithms #Strings
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