🚀 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
Mastering String Merging with StringBuilder
More Relevant Posts
-
📅 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
-
-
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
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 31 of #LeetCode Challenge 🔍 Problem: Decode the Slanted Ciphertext Today’s problem was all about understanding patterns and matrix traversal in a clever way! 💡 Key Idea: * The encoded string is formed by writing characters in a matrix row-wise * The trick is to read diagonally (↘️ direction) to decode the original message * No need to build a 2D matrix — we can directly calculate indices! 🧠 What I Learned: * How to convert 1D string into virtual 2D matrix * Diagonal traversal techniques * Importance of trimming trailing spaces in string problems ⚡️ Approach: * Calculate number of columns → cols = n / rows * Traverse diagonally from each column * Append characters using index formula i * cols + j * Remove extra spaces at the end 💻 Language: Java 🎯 Time Complexity: O(n) 📦 Space Complexity: O(n) Consistency is the key 🔑 — one problem at a time, getting better every day! #Day31 #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 21/30 – DSA Challenge 📌 LeetCode Problem – Median of Two Sorted Arrays 📝 Problem Statement Given two sorted arrays nums1 and nums2, find the median of the combined array. 📌 Example Input: nums1 = [1,2] nums2 = [3,4] Output: 2.5 💡 My Approach Instead of using complex binary search, I followed a simple and reliable method: 👉 Merge both arrays 👉 Sort the merged array 👉 Find the median This approach is easy to understand and implement. 🚀 Algorithm 1️⃣ Create a new array of size n1 + n2 2️⃣ Copy elements of both arrays 3️⃣ Sort the merged array 4️⃣ If length is odd → return middle element 5️⃣ If even → return average of two middle elements ✅ Java Code import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] merged = new int[n1 + n2]; for (int i = 0; i < n1; i++) { merged[i] = nums1[i]; } for (int i = 0; i < n2; i++) { merged[n1 + i] = nums2[i]; } Arrays.sort(merged); int n = merged.length; if (n % 2 == 1) { return merged[n / 2]; } else { return (merged[n / 2 - 1] + merged[n / 2]) / 2.0; } } } ⏱ Complexity Time Complexity: O((n + m) log(n + m)) Space Complexity: O(n + m) 📚 Key Learnings – Day 21 ✔ Simple solutions are often easiest to implement ✔ Always understand problem constraints ✔ This problem can be optimized further using binary search ✔ Multiple approaches exist — choose based on context Simple approach. Clear logic. Strong understanding. Day 21 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
**Day 110 of #365DaysOfLeetCode Challenge** Today’s problem: **Add Two Numbers II (LeetCode 445)** A very elegant **Linked List + Stack** problem. We are given two numbers stored in linked lists where the **most significant digit comes first**. Example: `7243 + 564 = 7807` Lists: `[7,2,4,3] + [5,6,4] = [7,8,0,7]` 💡 **Core Challenge:** Normally addition starts from the **last digit**… But linked lists are given from the **front**. So how do we add from right to left **without reversing the lists**? 📌 **Approach:** 1️⃣ Push digits of both linked lists into stacks 2️⃣ Pop from stacks → gives digits from right to left 3️⃣ Add with carry 4️⃣ Insert new node at the front of result list This preserves correct order naturally ⚡ **Time Complexity:** O(n + m) ⚡ **Space Complexity:** O(n + m) **What I learned today:** Stacks are incredibly useful when you need to process data in **reverse order**. 💭 **Key Takeaway:** If you can’t move backward easily: 👉 Use a stack 👉 Simulate reverse traversal 👉 Build result from front Clean solution. Smart idea. Great interview problem #LeetCode #DSA #LinkedList #Stack #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
**Day 109 of #365DaysOfLeetCode Challenge** Today’s problem: **132 Pattern (LeetCode 456)** This problem looks tricky at first because it asks for a hidden subsequence: Find indices `i < j < k` such that: `nums[i] < nums[k] < nums[j]` That forms the **132 pattern** 💡 **Core Idea: Use a Monotonic Stack** Instead of checking all triplets (**O(n³)** ❌), we scan from **right to left**. Why reverse? Because while moving backward: * We try to build possible `3` values using a stack * Track the best possible `2` using a variable called `third` 👉 If we ever find a number smaller than `third`, then: `nums[i] < third < nums[j]` 📌 **Approach:** * Traverse from end to start * Maintain decreasing stack * Pop smaller elements and update `third` * If current number < `third` → return true ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Some array problems become much easier when traversed **backward instead of forward**. 💭 **Key Takeaway:** When the problem asks for hidden order relations: 👉 Think stacks 👉 Think reverse traversal 👉 Think maintaining candidates dynamically This was a great reminder that brute force is rarely the final answer #LeetCode #DSA #MonotonicStack #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 15 – ArrayList vs LinkedList (It’s Not Just About Syntax) Today I explored the real difference between "ArrayList" and "LinkedList". List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new LinkedList<>(); At first glance, both implement "List"… but internally they are very different. --- 💡 ArrayList ✔ Backed by a dynamic array ✔ Fast for random access (get by index) ✔ Slower for insert/delete in middle (shifting required) --- 💡 LinkedList ✔ Uses a doubly linked list ✔ Faster for insert/delete (no shifting) ✔ Slower for access (traversal needed) --- ⚠️ Real insight: In most real-world scenarios, "ArrayList" is preferred due to better cache locality and overall performance. 👉 "LinkedList" is useful only when: - Frequent insertions/deletions in the middle - Less need for random access --- 💡 Takeaway: Don’t choose based on interface—choose based on use case and internal behavior #Java #BackendDevelopment #Collections #ArrayList #LearningInPublic
To view or add a comment, sign in
-
⏳ Day 20 – 1 Minute Java Clarity – Method Overloading vs Overriding Same name… totally different behaviour! 🤯 📌 What is Method Overloading? Same method name — different parameters — in the SAME class. 👉 Decided at Compile Time → Static Polymorphism. 📌 Example: class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 👉 Java picks the right method based on arguments you pass ✅ 📌 What is Method Overriding? Child class provides its OWN implementation of a parent class method. 👉 Decided at Runtime → Dynamic Polymorphism. 📌 Example: class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks!"); } } Animal a = new Dog(); a.sound(); // Output: Dog barks! ✅ 💡 Real-time Example: Overloading → Same coffee machine ☕ Small cup button → 100ml Large cup button → 300ml Same button name, different output based on input! Overriding → Company policy 📋 Head office says "work 9 to 5" Branch office overrides → "work 8 to 4" Same rule name, child changes the behaviour! ⚠️ Interview Trap: Can we override a static method? 👉 No! Static methods belong to the class — not the object. 👉 It's called Method Hiding, not Overriding! 💡 Quick Summary: | Feature | Overloading | Overriding | | Class | Same | Parent & Child | | Parameters | Different | Same | | Time | Compile time | Runtime | | Keyword | None | @Override | 🔹 Next Topic → Polymorphism in Java Which one confuses you more — overloading or overriding? Drop 👇 #Java #JavaProgramming #MethodOverloading #MethodOverriding #OOPs #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
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