Day 36 of Daily DSA 🚀 Solved LeetCode 443: String Compression ✅ Problem: Given an array of characters, compress it in-place using run-length encoding. Each group of consecutive repeating characters is replaced by the character followed by its count (if count > 1). The result must be stored back in the input array. Rules: * If a group's length is 1 → append only the character * If a group's length is > 1 → append character + count * Group lengths ≥ 10 are split into multiple characters * Must use only constant extra space * Return the new length of the array Approach: Used a StringBuilder to build the compressed string by tracking consecutive character counts, then wrote the result back into the input array. Steps: 1. Append the first character to StringBuilder 2. Iterate through the array counting consecutive duplicates 3. On a new character → if count > 1, append the count 4. Append the new character and reset count 5. Handle the last group after the loop 6. Write compressed characters back into the input array ⏱ Complexity: • Time: O(n) • Space: O(n) (StringBuilder) 📊 LeetCode Stats: • Runtime: 3 ms (Beats 12.04%) • Memory: 45.58 MB (Beats 42.35%) A great exercise in in-place array manipulation and run-length encoding — fundamentals that show up everywhere in data compression. #DSA #LeetCode #Java #Strings #RunLengthEncoding #CodingJourney #ProblemSolving
LeetCode 443: String Compression in Java
More Relevant Posts
-
🔥 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
-
-
The High Cost of the Wrong Initial Choice I have seen complex computation logic for over a million records take hours to run simply because of inefficient, row-by-row processing that is offered by database stored procedures and traditional java/python code. It is slow, impossible to scale, and eventually kills your product's edge in the market. By moving to vectorized logic with tools like NumPy or Polars, you can turn those hours of computation into milliseconds. This is not just about using newer tools, it is about leveraging modern execution like #SIMD (Single Instruction Multiple Data) and #multithreading to gain a massive competitive advantage. If your backend is computation heavy and you're still stuck in legacy loops, you are leaving performance, market edge and money on the table. References: https://lnkd.in/g8j3A5Bn https://lnkd.in/gaPnFUQm https://lnkd.in/gWt9WHnp #DataEngineering #SystemDesign #NumPy #PerformanceOptimization #Scalability #PythonProgramming #TechStrategy #Vectorization #TechToolChoice
To view or add a comment, sign in
-
🔥 DSA Challenge – Day 128/360 🚀 📌 Topic: Recursion 🧩 Problem: Letter Combinations of a Phone Number 💡 Problem Statement: Given a string of digits (2–9), return all possible letter combinations that the number could represent based on the classic phone keypad mapping. 🔍 Example: Input: "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 💡 Approach: Backtracking (Recursion) We treat this like a decision tree: Each digit maps to multiple characters For every digit, we try all possible letters Build combinations step-by-step using recursion 👉 Key Idea: Choose → Explore → Backtrack Use StringBuilder for efficient string manipulation ⚙️ Steps: Create a mapping for digits → letters Start recursion from index 0 For each digit: Loop through its mapped letters Add letter to current string Move to next digit Backtrack (remove last character) 🚀 Code Highlights: ✔️ Base case: when index reaches end → add combination ✔️ Efficient backtracking using StringBuilder ✔️ Avoids extra space by modifying same string ⏱️ Time Complexity: O(4^N) 📦 Space Complexity: O(N) (recursion stack) Master this → You master recursion 🔥 #DSA #Java #Backtracking #CodingInterview #LeetCode #128DaysOfCode #Programming #Tech #ProblemSolving
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 – 𝐃𝐞𝐜𝐨𝐝𝐞 𝐭𝐡𝐞 𝐒𝐥𝐚𝐧𝐭𝐞𝐝 𝐂𝐢𝐩𝐡𝐞𝐫𝐭𝐞𝐱𝐭 (𝐌𝐞𝐝𝐢𝐮𝐦) Today’s problem was a 𝐟𝐮𝐧 𝐦𝐚𝐭𝐫𝐢𝐱 𝐭𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥 + 𝐬𝐢𝐦𝐮𝐥𝐚𝐭𝐢𝐨𝐧 𝐜𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐋𝐢𝐧𝐤 : https://lnkd.in/gsSCrJbr 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐋𝐢𝐧𝐤 : https://lnkd.in/gMhqhD6M The idea behind the encoding process: The original text is written 𝐝𝐢𝐚𝐠𝐨𝐧𝐚𝐥𝐥𝐲 𝐢𝐧 𝐚 𝐦𝐚𝐭𝐫𝐢𝐱 with a fixed number of rows. The matrix is then read row by row to produce the encoded string. To decode it, we reverse the process: 🔹 𝐊𝐞𝐲 𝐎𝐛𝐬𝐞𝐫𝐯𝐚𝐭𝐢𝐨𝐧𝐬 If n = encodedText.length() and we know rows, then cols = n / rows Characters of the original text lie on diagonals starting from each column in the first row. Traverse diagonally (row++, col++) from each starting column. 🔹 𝐒𝐭𝐞𝐩𝐬 Compute the number of columns. For every column c, traverse diagonally down-right. Map the matrix index using r * cols + c. Build the result string. Remove trailing spaces at the end. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 Time: O(n) Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲: Whenever you see a matrix encoding problem, think about how the data was written and reverse the traversal pattern. #LeetCode #CodingInterview #DataStructures #Algorithms #Java #ProblemSolving #DailyCodingChallenge
To view or add a comment, sign in
-
-
Problem :- Remove Duplicates from Sorted Array (LeetCode 26) Problem Statement :- Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements. The relative order of elements should be kept the same. Approach :- Two Pointer Technique i - Use pointer k to track position of unique elements ii - Traverse array from index 1 iii - If nums[i] != nums[k-1], place it at nums[k] iv - Time Complexity : O(n) v - Space Complexity : O(1) class Solution { public int removeDuplicates(int[] nums) { int k = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[k - 1]) { nums[k] = nums[i]; k++; } } return k; } } Key Takeaway :- Since the array is already sorted, duplicates are adjacent. Using two pointers allows us to efficiently overwrite duplicates in a single pass without extra space. If yes, how would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟱/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 72. Edit Distance 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given two strings word1 and word2, compute the minimum number of operations required to convert word1 into word2. Allowed operations: • Insert a character • Delete a character • Replace a character 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: This is a Dynamic Programming problem. • Define a 2D DP array where dp[i][j] represents the minimum operations needed to convert the first i characters of word1 to the first j characters of word2 • Initialization: – dp[i][0] = i → delete all characters – dp[0][j] = j → insert all characters • Transition: – If characters match: dp[i][j] = dp[i-1][j-1] – If characters differ: dp[i][j] = 1 + min( dp[i-1][j-1], // replace dp[i-1][j], // delete dp[i][j-1] // insert ) • Final answer: dp[m][n] This works because at each step, we choose the optimal operation among insert, delete, or replace based on previously computed subproblems. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(m × n) • Space Complexity: O(m × n) 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: When transforming one string into another, think in terms of prefix transformations and build solutions bottom-up using DP. Problems involving string edits often reduce to comparing characters and choosing optimal operations. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/g8MzA3Rm #Day65of75 #LeetCode75 #DSA #Java #Python #DynamicProgramming #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
Day 105: Circular Arrays & Shortest Paths 🔄 Problem 2515: Shortest Distance to Target String in a Circular Array Today’s challenge involved finding the minimum steps to reach a target string in a circular array, allowing movement in both directions. The Strategy: • Bidirectional Search: Since the array is circular, the distance can be calculated in two ways: moving forward or moving backward. • Modular Arithmetic: I used (dist + n) % n to handle the wrap-around logic seamlessly, ensuring the index stays within bounds regardless of the direction. • Optimization: By iterating once through the array and comparing the distances for every occurrence of the target, I maintained an O(N) time complexity. Sometimes the most elegant way to handle a "circular" problem is simply embracing the symmetry of the path. 🚀 #LeetCode #Java #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
#Day74 of my second #100DaysOfCode Binary search variations getting more interesting now. DSA • Solved Find Minimum in Rotated Sorted Array (LeetCode 153) – Brute: linear scan → O(n) – Optimal: binary search with an early check for already sorted part → O(log n) • Key idea: the minimum always lies in the unsorted portion, and if a part is already sorted, the answer can be taken directly • Difference from previous problems: instead of searching for a target, we’re tracking the minimum while narrowing the search space • Edge cases: – already sorted array – single element case – careful updates while narrowing the range This one was more about understanding the pattern than just applying binary search. #DSA #BinarySearch #LeetCode #Algorithms #Java #100DaysOfCode #WomenWhoCode #BuildInPublic #LearningInPublic
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 127/360 🚀 📌 Topic: Backtracking 🧩 Problem: Subsets II Problem Statement: Given an integer array that may contain duplicates, return all possible subsets such that the solution set does not contain duplicate subsets. 🔍 Example: Input: nums = [1,2,2] Output: [[], [1], [1,2], [1,2,2], [2], [2,2]] 💡 Approach: Backtracking + Sorting 1️⃣ Step 1 – Sort the array to group duplicate elements together 2️⃣ Step 2 – Use recursion to generate all subsets 3️⃣ Step 3 – Skip duplicate elements using condition (i != ind && nums[i] == nums[i-1]) ⏱ Complexity: Time: O(2^n) Space: O(n) (recursion stack + subset storage) 📚 Key Learning: Sorting + smart skipping of duplicates helps avoid repeated subsets in backtracking problems. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #360DaysOfCode #LeetCode #Backtracking
To view or add a comment, sign in
-
-
🚀 Solved: Trapping Rain Water Problem (Optimized Approach) Today, I tackled another classic problem from LeetCode — Trapping Rain Water. 🔍 Problem Statement Given an array representing elevation heights, compute how much water can be trapped after raining. 💡 Approach Used: Prefix Max Arrays Instead of checking water at each position repeatedly (which can be inefficient), I used a precomputation strategy: -> Compute the tallest bar on the left for every index -> Compute the tallest bar on the right for every index -> Water trapped at index i = min(leftMax, rightMax) - height[i] ⚡ Time Complexity: O(N) 📦 Space Complexity: O(N) 💻 Java Implementation: class Solution { public int trap(int[] height) { if (height == null || height.length == 0) { return 0; } int n = height.length; int[] maxL = new int[n]; int[] maxR = new int[n]; maxL[0] = height[0]; for (int i = 1; i < n; i++) { maxL[i] = Math.max(maxL[i - 1], height[i]); } maxR[n - 1] = height[n - 1]; for (int j = n - 2; j >= 0; j--) { maxR[j] = Math.max(maxR[j + 1], height[j]); } int water = 0; for (int i = 0; i < n; i++) { water += (Math.min(maxL[i], maxR[i]) - height[i]); } return water; } } 🎯 Key Insight: Water trapped at any index depends on the minimum of the tallest bars on both sides, not just local heights. #Java #DataStructures #Algorithms #LeetCode #CodingInterview #SoftwareEngineering #ProblemSolving
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