🚀 Day 78 of #100DaysOfCode Solved 443. String Compression on LeetCode 🔗 🧠 Key Insight: We compress the array in-place by: 👉 Replacing consecutive characters with: char + count (if count > 1) Example: ["a","a","b","b","c","c","c"] → ["a","2","b","2","c","3"] ⚙️ Approach (Two Pointers): 1️⃣ Use two pointers: 🔹 i → iterate through array 🔹 idx → position to write compressed result 2️⃣ For each character: 🔹 Count consecutive occurrences using a loop 3️⃣ Write character: 🔹 chars[idx++] = ch 4️⃣ If count > 1: 🔹 Convert count to string 🔹 Add each digit to array 5️⃣ Continue until end 6️⃣ Return idx (new length) ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #Strings #TwoPointers #Array #Java #InterviewPrep #CodingJourney
Solved 443. String Compression on LeetCode with Two Pointers Approach
More Relevant Posts
-
**Day 104 of #365DaysOfLeetCode Challenge** Today’s problem: **String Compression (LeetCode 443)** A classic **Two Pointer + In-place manipulation** problem that tests how efficiently you can work with arrays without extra space. 💡 **Core Idea:** We compress the string by grouping **consecutive repeating characters**: * If count = 1 → just write the character * If count > 1 → write character + count 👉 And the catch? Do everything **in-place (O(1) extra space)** 📌 **Approach:** * Use two pointers: * `i` → to traverse the array * `index` → to write compressed result * Count consecutive characters * Write character and its frequency (if >1) * Convert count to string and insert digit by digit ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(1) **What I learned today:** In-place problems are all about **careful pointer management**. 💭 **Key Takeaway:** When asked to modify arrays without extra space: 👉 Think **read pointer + write pointer** These small optimizations make a huge difference in interviews #LeetCode #DSA #TwoPointers #Strings #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Day 44 of Daily DSA 🚀 Solved LeetCode 1572: Matrix Diagonal Sum ✅ Problem: Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Approach: Used a two-pointer technique to traverse both diagonals in a single pass. Steps: Initialize two pointers → start = 0, end = n-1 Traverse each row: Add mat[i][start] (primary diagonal) Add mat[i][end] (secondary diagonal) Move pointers: start++, end-- If matrix size is odd → add center element once ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.53 MB Optimizing nested loops into a single pass can make your solution both cleaner and faster 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
The Two-Pointer streak continues! Today’s LeetCode Problem: Is Subsequence. After using multiple pointers to sort arrays and move zeroes, I applied the exact same pattern to string manipulation today. The challenge was figuring out if a shorter string (s) is a valid subsequence of a longer string (t) without disturbing the relative order of the characters. Instead of generating all possible subsequences (which would be a massive O(2ⁿ) performance drain), the Two-Pointer approach solves this beautifully in a single pass. Knocking this out in O(n) time and O(1) space is another great reminder of how incredibly versatile this algorithmic pattern is for both arrays and strings. #DSA #Java #LeetCode #IsSebsequenceProblem
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 87 - Convert Sorted Array to Binary Search Tree Converted a sorted array into a height-balanced BST. Approach: • Pick middle element as root • Recursively build left subtree from left half • Recursively build right subtree from right half Middle element ensures balanced height Time Complexity: O(n) Space Complexity: O(h) #Day87 #LeetCode #BST #BinaryTree #DSA #Java #CodingJourney
To view or add a comment, sign in
-
-
Some problems break the standard sliding window pattern — especially when negative numbers are involved. 🚀 Day 104/365 — DSA Challenge Solved: Shortest Subarray with Sum at Least K Problem idea: We need to find the length of the shortest subarray whose sum is at least k. The challenge is that the array can contain negative numbers, so normal sliding window won't work. Efficient approach: Use Prefix Sum + Monotonic Deque. Steps: 1. Build a prefix sum array 2. Use a deque to store indices of useful prefix sums 3. While current sum − smallest prefix ≥ k → update answer 4. Maintain increasing order in deque by removing larger prefix sums from the back 5. This ensures we always get the shortest valid subarray This approach efficiently handles negative numbers while keeping optimal time complexity. ⏱ Time: O(n) 📦 Space: O(n) Day 104/365 complete. 💻 261 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #Deque #PrefixSum #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
Most substring problems can be solved efficiently using the sliding window technique. 🚀 Day 97/365 — DSA Challenge Solved: Longest Substring Without Repeating Characters Problem idea: We need to find the length of the longest substring that contains no duplicate characters. Efficient approach: Use a sliding window with two pointers. Steps: 1. Keep track of the last seen index of each character 2. Expand the window by moving the right pointer 3. If a character repeats inside the window, move the left pointer to the position after its last occurrence 4. Update the maximum window length This ensures the window always contains unique characters. ⏱ Time: O(n) 📦 Space: O(1) Day 97/365 complete. 💻 268 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
✨ Day 42 of 90 – Pattern Mastery Journey 🧠 Pattern : Alphabet Hash Pattern 💡 Approach: ✔ Created an n × n matrix using nested loops ✔ Printed alphabets only when row index equals column index (i == j) ✔ Filled all other positions with `#` ✔ Used ASCII logic `(char)('A' + i - 1)` to generate characters 🚀 This problem helped me understand how **diagonal conditions work in matrices** and how simple conditions can create clean structured patterns. #PatternMasteryJourney #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟔𝟕 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding the smallest subarray with sum ≥ target. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Minimum Size Subarray Sum 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐒𝐥𝐢𝐝𝐢𝐧𝐠 𝐖𝐢𝐧𝐝𝐨𝐰 • Maintained a window using two pointers (left & right) • Expanded the window by moving right pointer • Once sum ≥ target: • Shrunk the window from the left • Updated the minimum length This ensures we always keep the smallest valid window. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Sliding window works well for subarray problems • Expand → to meet condition • Shrink → to optimize result • Two pointers reduce time complexity significantly 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Sliding window is about balance — expand when needed, shrink when possible. 67 days consistent 🚀 On to Day 68. #DSA #Arrays #SlidingWindow #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day 59/75 — Merge Sorted Array Today’s problem was about merging two sorted arrays into one sorted array in-place. Approach: • Start from the end to avoid overwriting elements • Use three pointers: i (nums1), j (nums2), k (merged position) • Place the larger element at the end and move backwards Key logic: while (i >= 0 && j >= 0) { if (nums1[i] > nums2[j]) { nums1[k--] = nums1[i--]; } else { nums1[k--] = nums2[j--]; } } while (j >= 0) { nums1[k--] = nums2[j--]; } Time Complexity: O(m + n) Space Complexity: O(1) A simple yet important problem that reinforces two-pointer technique. 59/75 🚀 #Day59 #DSA #TwoPointers #Arrays #Java #Algorithms #LeetCode
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