🚀 Leetcode : 1768. Merge Strings Alternately Ever needed to merge two strings by alternating their characters? Here's a simple and optimized approach using StringBuilder in Java 👇 💡 What this solution does: Takes two input strings Merges them character by character in alternating order Handles unequal lengths gracefully 🔍 Key Highlights: Uses StringBuilder for better performance (avoids unnecessary string creation) Single loop with clean condition (i < n1 || i < n2) Easy to read and efficient 📌 Example: Input: "abc", "pqrstu" Output: "apbqcrstu" ⚙️ Complexity Analysis: Time Complexity: O(n + m) 👉 We traverse both strings once (n = length of word1, m = length of word2) Space Complexity: O(n + m) 👉 Because we store the final merged string in StringBuilder #Java #Coding #Programming #LeetCode #DataStructures #Algorithms #ProblemSolving #Developer #StringManipulation #CleanCode #Tech #TimeComplexity #SpaceComplexity #SoftwareEngineering #DevLife #CodeNewbie #100DaysOfCode #TechCommunity #ProgrammingLife #DevelopersLife #TowPointer 🚀
LeetCode 1768: Merge Strings Alternately with Java
More Relevant Posts
-
🚀 Day 536 of #750DaysOfCode 🚀 Today I solved Count Submatrices With Equal Frequency of X and Y (LeetCode 3212) using Java. 🔹 Problem Summary: Given a grid containing 'X', 'Y', and '.', we need to count the number of submatrices starting from the top-left corner (0,0) such that: • The number of 'X' and 'Y' is equal • The submatrix contains at least one 'X' 🔹 Approach: Instead of checking every possible submatrix (which would be too slow), I used the Prefix Sum technique. I maintained two prefix matrices to store the count of 'X' and 'Y' up to each cell. For every position (i, j), I checked: countX == countY and countX > 0 If true, that submatrix is valid. This reduces the complexity to O(n × m), which works efficiently for large grids. 🔹 Key Concepts Learned: ✅ Prefix Sum in 2D ✅ Matrix traversal optimization ✅ Handling constraints up to 1000 × 1000 ✅ Clean implementation in Java Consistent practice is making problem-solving faster and more structured every day. #750DaysOfCode #Day536 #LeetCode #Java #DataStructures #Algorithms #PrefixSum #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
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
-
-
🚀 Day 15 of #50DaysLeetCode Challenge Today I solved the “Longest Common Prefix” problem on LeetCode using Java. 🔹 Problem: Find the longest common prefix among an array of strings. If no common prefix exists, return an empty string "". Example: Input: ["flower","flow","flight"] Output: "fl" Input: ["dog","racecar","car"] Output: "" 🔹 Approach I Used: ✔ Took the first string as the initial prefix ✔ Compared it with each string in the array ✔ If mismatch occurs, reduced the prefix step by step ✔ Continued until all strings share the same prefix 🔹 Key Insight: You don’t need complex logic — just keep shrinking the prefix until it matches all strings. 🔹 Concepts Practiced: • String manipulation • Iterative comparison • Edge case handling #LeetCode #DSA #Java #Algorithms #ProblemSolving #CodingChallenge #50DaysOfCode
To view or add a comment, sign in
-
-
🔥 𝗗𝗮𝘆 𝟵𝟯/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟭𝟲𝟬𝟴. 𝗦𝗽𝗲𝗰𝗶𝗮𝗹 𝗔𝗿𝗿𝗮𝘆 𝗪𝗶𝘁𝗵 𝗫 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 𝗚𝗿𝗲𝗮𝘁𝗲𝗿 𝗧𝗵𝗮𝗻 𝗼𝗿 𝗘𝗾𝘂𝗮𝗹 𝗫 | 🟢 Easy | Java A self-referential condition — x elements must be ≥ x. Elegant problem, elegant solution. 🎯 🔍 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Find x such that exactly x elements in the array are ≥ x. Return -1 if no such x exists. ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗙𝗿𝗲𝗾𝘂𝗲𝗻𝗰𝘆 𝗖𝗼𝘂𝗻𝘁 + 𝗦𝘂𝗳𝗳𝗶𝘅 𝗦𝘂𝗺 ✅ Cap all values at n (array length) — anything larger contributes the same way ✅ Build a frequency count array of size n+1 ✅ Traverse from right to left, accumulating a running suffix sum ✅ When suffix sum == current index i → x = i is the answer! 💡 𝗪𝗵𝘆 𝗰𝗮𝗽 𝗮𝘁 𝗻? x can never exceed n (can't have more elements than the array size). So values above n are equivalent — capping them avoids index overflow and keeps the logic clean. 📊 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 ⏱ Time: O(n) — two passes 📦 Space: O(n) — frequency array No sorting. No binary search. Just a clever frequency count + suffix accumulation. Sometimes the cleanest approach is right under your nose. 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gm2c4-6x 𝟳 𝗺𝗼𝗿𝗲 𝗱𝗮𝘆𝘀. 𝗦𝗼 𝗰𝗹𝗼𝘀𝗲 𝘁𝗼 𝟭𝟬𝟬! 💪 #LeetCode #Day93of100 #100DaysOfCode #Java #DSA #Arrays #FrequencyCount #CodingChallenge #Programming
To view or add a comment, sign in
-
🚀 Day 538 of #750DaysOfCode 🚀 Today I solved Flip Square Submatrix Vertically (LeetCode 3643) using Java. 🔹 Problem Summary: Given a matrix and a square submatrix defined by top-left corner (x, y) and size k, we need to flip that square vertically. Flipping vertically means reversing the order of rows inside the selected k × k submatrix while keeping the rest of the matrix unchanged. 🔹 Approach Used: I used a two-pointer approach to swap rows inside the square: • One pointer at the top row • One pointer at the bottom row • Swap elements column by column inside the square • Move pointers towards the center This way, the submatrix gets flipped vertically in-place without extra space. 🔹 Key Concepts Learned: ✅ Matrix traversal ✅ Submatrix manipulation ✅ Two-pointer technique ✅ In-place swapping ✅ Clean implementation in Java Small problems like this help in mastering matrix operations, which are very common in coding interviews. #750DaysOfCode #Day538 #LeetCode #Java #DSA #Algorithms #CodingChallenge #Matrix #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
DAY 5 of #100DaysOfLeetCode Today, I tackled the Trapping Rain Water Problem (LeetCode Hard), a classic challenge that tests your understanding of arrays and optimization. Approach Used: Prefix Max Arrays Instead of using a brute force method, I optimized the solution with two auxiliary arrays: - leftMax[] → stores the maximum height from the left - rightMax[] → stores the maximum height from the right Key Insight: Water trapped at any index is calculated as: min(leftMax[i], rightMax[i]) - height[i] This formula ensures we only count the water that can actually be held between boundaries. Time Complexity: O(n) Space Complexity: O(n) Here’s the clean Java implementation: class Solution { public int trap(int[] height) { int n = height.length; int[] leftMax = new int[n]; int[] rightMax = new int[n]; leftMax[0] = height[0]; for(int i=1; i<n; i++){ leftMax[i] = Math.max(leftMax[i-1], height[i]); } rightMax[n-1] = height[n-1]; for(int i=n-2; i>=0; i--){ rightMax[i] = Math.max(rightMax[i+1], height[i]); } int totalWater = 0; for(int i=0; i<n; i++){ totalWater += Math.min(leftMax[i], rightMax[i]) - height[i]; } return totalWater; } } #LeetCode #DataStructures #Algorithms #Java #CodingInterview #SoftwareEngineer #TechJobs #TorontoTech #CanadaJobs #WomenInTech #CodeNewbie #Programming #DeveloperJourney #JobSearch #BackendDeveloper #InterviewPrep Always open to feedback and discussions—feel free to share your approach!
To view or add a comment, sign in
-
-
Read a sensor value. Save it to a database. In Python that's 4 lines. Java: 12. C#: 8. Go: 6. Each looks completely different. Each needs a developer who knows that specific stack. Developer leaves? New one prefers something else. Rewrite. The logic never changed. But the implementation is tied to whoever wrote it. That's what visual development actually solves. Not "easier." Independent. #SoftwareArchitecture #NoCode #Manufacturing
To view or add a comment, sign in
-
-
🚀 DSA Series – Longest Common Prefix 📌 Problem: Given an array of strings, the task is to find the longest common prefix shared by all the strings. If there is no common prefix, return an empty string "". Example: Input: "["flower","flow","flight"]" Output: ""fl"" Input: "["dog","racecar","car"]" Output: """" (no common prefix) 💡 Approach Used (Character by Character Comparison): 1️⃣ Take the first string in the array as a reference. 2️⃣ Traverse its characters one by one. 3️⃣ For each character, compare it with the same position in all other strings. 4️⃣ If any string has: - a different character, or - the length is smaller, then stop and return the prefix built so far. If all characters match across every string, keep adding them to the prefix. This approach checks characters column-wise across all strings. ⚡ Time Complexity: O(n × m) - n = number of strings - m = length of the smallest string ⚡ Space Complexity: O(1) #DSASeries #LeetCode #Java #CodingPractice #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 11 of #50DaysLeetCode Challenge Today I tackled a HARD problem: “Regular Expression Matching” on LeetCode using Java. 🔹 Problem: Given a string "s" and a pattern "p", implement regex matching with support for: • "." → matches any single character • "*" → matches zero or more of the preceding element Return true if the entire string matches the pattern. Example: Input: "s = "aa", p = "a*"" → Output: "true" Input: "s = "aa", p = "a"" → Output: "false" 🔹 Approach I Used: I used Dynamic Programming (DP) — anything else here is inefficient or breaks on edge cases. ✔ Created a 2D DP table "dp[m+1][n+1]" ✔ "dp[i][j]" represents whether "s[0...i-1]" matches "p[0...j-1]" ✔ Handled "*" carefully: - Treat it as zero occurrence → "dp[i][j-2]" - Or one/more occurrence → match previous character ✔ Built the solution bottom-up 🔹 Concepts Practiced: • Dynamic Programming (2D DP) • String pattern matching • Handling complex edge cases #LeetCode #DSA #Java #DynamicProgramming #Algorithms #CodingChallenge #50DaysOfCode
To view or add a comment, sign in
-
-
Refactoring for Clarity: Array Manipulation in Java 👨💻 I’ve just finished a practical exercise on array manipulation. While the goal was simple (summing two arrays), I used it as an opportunity to apply improvements. - Method decomposition: Separated concerns into specialized methods (Read, Calculate, Display). - Input validation: Built a robust loop to handle invalid inputs and prevent crashes. - Data Formatting: Used printf to create a clear, readable results table. Small improvements in logic and organization make a huge difference in software quality. #Java #Algorithms #CleanCode #Backend #LearningToCode
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