🌟 Day 31 of #100DaysOfCode 🌟 🔍 Backspace String Compare — Stack Logic & Two-Pointer Optimization 🔹 What I Solved Today, I solved the “Backspace String Compare” problem — an elegant challenge that simulates typing behavior in text editors. The twist? The # symbol acts as a backspace, and we must determine if two strings are equal after applying all backspaces. 📝 Problem Statement Given two strings s and t, return true if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: s = "ab#c", t = "ad#c" Output: true Explanation: Both become "ac". Example 2: Input: s = "ab##", t = "c#d#" Output: true Explanation: Both become "". Example 3: Input: s = "a#c", t = "b" Output: false Explanation: s = "c", t = "b". 🧠 Concepts Used Stack / StringBuilder for backspace simulation Character traversal from left to right Two-pointer optimization (O(1) space approach) String manipulation & comparison ⚙️ Approach 1️⃣ Traverse each string and simulate typing: • If the character isn’t #, add it. • If it’s #, remove the last character (if present). 2️⃣ Compare the final processed versions of both strings. 3️⃣ Alternatively, use a two-pointer approach from the end for constant space optimization. 🚀 What I Learned Small-looking problems can teach efficient simulation techniques. Understanding string traversal logic is crucial for interview-ready problem solving. #100DaysOfCode #Java #ProblemSolving #CodingJourney #LeetCode #Algorithms #Strings #Stack #TwoPointers #CodingChallenge #KeepBuilding
Garvit Pant’s Post
More Relevant Posts
-
#100DaysOfCode – Day 66 String Manipulation & Primitive Decomposition 🧩 Task: Given a valid parentheses string, decompose it into its primitive components and then remove the outermost parentheses from each component. Example: Input: s = "(()())(())" Primitive Decomposition: "(()())" + "(())" After removing outermost parentheses: "()()" + "()" Output: "()()()" My Approach: I iterated through the string while keeping a counter to track the balance of open parentheses. When an opening parenthesis ( was found, I incremented the counter. If the count was greater than 1, it meant this parenthesis was not an outermost one, so I appended it to the result. When a closing parenthesis ) was found, I only appended it if the counter was greater than 1 before decrementing. This ensures the final closing parenthesis of a primitive part is excluded. This simple counter-based approach effectively identifies and removes the correct parentheses without needing a more complex data structure like a stack. Time Complexity: O(N) Space Complexity: O(N) Sometimes, a simple counter is all you need to elegantly handle nested structures. It can be a clean and efficient alternative to more complex data structures for certain problems. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #DataStructures #Algorithms #StringManipulation #CodeNewbie
To view or add a comment, sign in
-
-
🌟 Day 28 of #100DaysOfCode 🌟 🔍 Reverse Words in a String — Clean & Elegant String Manipulation 🔹 What I Solved Today, I solved the classic “Reverse Words in a String” problem — a deceptively simple challenge that tests your understanding of string manipulation, trimming spaces, and efficient iteration. This problem is all about cleaning messy input and reordering data logically, which is a valuable skill in real-world text processing tasks. 📝 Problem Statement Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The returned string should have only a single space separating words — with no leading or trailing spaces. Example 1: Input: s = "the sky is blue" Output: blue is sky the Example 2: Input: s = " hello world " Output: world hello Example 3: Input: s = "a good example" Output: example good a 🧠 Concepts Used String Splitting & Trimming Whitespace Handling Iteration & StringBuilder Efficient Memory Management ⚙️ Approach 1️⃣ Trim the string to remove extra leading/trailing spaces. 2️⃣ Split the string by one or more spaces using regex (\\s+). 3️⃣ Iterate backward through the words array. 4️⃣ Append words to a StringBuilder, adding spaces only between words. 5️⃣ Return the final reversed and clean string. 🚀 What I Learned This problem reinforced how attention to detail matters in coding — especially when handling strings and whitespace. It also reminded me that even simple problems can teach clean code principles, edge case thinking, and time-space optimization. Grateful to K.R. Mangalam University for continuously motivating me on this journey of learning and consistency. #100DaysOfCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🚩 Problem: 153. Find Minimum in Rotated Sorted Array 🔥 Day 59 of #100DaysOfLeetCode 🔍 Problem Summary: You’re given a rotated sorted array of unique integers. Your task: find the minimum element in O(log n) time. Example of rotated array: [4,5,6,7,0,1,2] → minimum = 0 🧠 Intuition: Because the array is originally sorted, rotation keeps two sorted halves. We can use binary search: Check if the mid element is part of the right sorted half Or the left sorted half Narrow down the search to where the rotation break happens The minimum is exactly at the rotation point Key observation: If nums[mid] > nums[right] → min is in the right half Else → min is in the left half Clean, elegant, and strictly log-time.⚙️ Performance: ⏱️ Runtime: 0 ms 🚀 💪 Beats: 100% of Java solutions 💾 Memory: 42 MB ⚡ (Beats 95%+ users) 📊 Complexity: Time Complexity: O(log n) Space Complexity: O(1) ✨ Key Takeaway: This is the perfect example of using binary search on conditions, not just sorted arrays. Mastering this pattern helps solve advanced problems on rotated arrays and search intervals. Link:[https://lnkd.in/ggdZwAKJ] #100DaysOfLeetCode #Day59 #Problem153 #FindMinimumInRotatedArray #BinarySearch #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #CrackingTheCodingInterview #BinarySearchPattern #CodingCommunity #SoftwareEngineering #DataStructures #DeveloperJourney #ArjunInfoSolution #TechCareers #CareerGrowth #Programming #ZeroToHero #LearnToCode #CodeNewbie #CodingIsFun #JavaDeveloper #GameDeveloper #Unity #AI #MachineLearning
To view or add a comment, sign in
-
-
#Day 1: Remove Duplicates from Sorted Array . "Marked Day 1 of my DSA journey with an O(n)time solution to the 'Remove Duplicates from Sorted Array' problem (LeetCode #26)." # Algorithm Choice: The Two-Pointers Technique Since the array is sorted, the most efficient solution is the Two-Pointers approach, which operates in-place. Pointers: A slow pointer (i) marks the position for the next unique element, and a fast pointer (j) iterates through the array to find new values. Logic: If nums[j] is different from nums[i], we found a unique value! We increment i and write nums[j] to nums[i]. We skip duplicates by simply advancing j. #CODE: class Solution { public int removeDuplicates(int[] nums) { int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j];} } return i + 1; }} #Time Complexity:O(n)-Optimal linear time, as we only traverse the array #.Space Complexity-O(1)-Solved in-place using constant extra memory. Solving this with an optimal O(n) time and O(1) space solution is a great start! What's your favorite O(1) space array trick? Share it below! 👇 #DSA #DailyChallenge #LeetCode #Java #Coding #TwoPointers #SoftwareEngineering #InterviewPrep
To view or add a comment, sign in
-
-
🚩 Problem: 56. Merge Intervals 🔥 Day 58 of #100DaysOfLeetCode 🔍 Problem Summary: You are given an array of intervals where each interval is [start, end]. Merge all overlapping intervals and return the result. 🧠 Intuition: This is a classic sorting + merging problem. Steps: Sort intervals based on starting time Traverse them one by one If the current interval overlaps with the previous one, merge them Otherwise, add the current interval as a new block The idea is extremely simple once sorted. 🔑 When do intervals overlap? If: current.start ≤ previous.end → merge Else → start a new interval blockPerformance: ⏱️ Runtime: 6 ms 🚀 💪 Beats: 97.5% of Java solutions 💾 Memory: 45 MB ⚡ (Beats ~93% of users) 📊 Complexity: Time Complexity: O(n log n) (due to sorting) Space Complexity: O(n) (result list) ✨ Key Takeaway: This problem teaches the powerful pattern: Sort → Sweep → Merge It’s used in many real-world applications: CPU scheduling Calendar merging Event time-line processing Data range compression A must-know for top interview rounds. Link:[https://lnkd.in/gCRpSVJW] #100DaysOfLeetCode #Day58 #Problem56 #MergeIntervals #Sorting #GreedyAlgorithms #DSA #Java #ProblemSolving #CodingChallenge #LeetCode #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DeveloperJourney #ArjunInfoSolution #TechCareers #CareerGrowth #DataStructures #Programming #ZeroToHero #CodeNewbie #LearnToCode #CodingIsFun #JavaDeveloper #GameDeveloper #Unity #AI #MachineLearning
To view or add a comment, sign in
-
-
🚩 Problem: 239. Sliding Window Maximum 🔥 Day 51 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return an array containing the maximum value in every sliding window of size k. This is a classic sliding window problem that looks heavy, but with the right data structure, the solution is clean and O(n). 🧠 Intuition: A normal approach checks each window → O(n × k) (too slow). Instead, use a Deque to store indices of useful elements: The deque always keeps elements in decreasing order. The front of the deque is always the maximum of the current window. Remove elements: Outside the current window Smaller than the new incoming element This gives us the maximum in O(1) per window ⇒ total O(n). ⚙️ Performance: ⏱️ Runtime: 28 ms 🚀 💪 Beats: 98.7% of Java solutions 💾 Memory: 63 MB ⚡ (Beats ~96% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(k) ✨ Key Takeaway: The Deque technique is one of the most powerful sliding window optimizations — turning a potentially quadratic problem into linear time with a clean and elegant solution. Link:[https://lnkd.in/gJTzhcR2] #100DaysOfLeetCode #Day51 #Problem239 #SlidingWindowMaximum #Deque #SlidingWindow #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #CodingCommunity #ArjunInfoSolution #CodeNewbie #Programming #TechCareers #CareerGrowth #ZeroToHero #LearnToCode #CodingIsFun #ComputerScience #JavaDeveloper #DeveloperJourney #AI #MachineLearning #UnityGameDev #GameDeveloper
To view or add a comment, sign in
-
-
🚩 Problem: 41. First Missing Positive 🔥 Day 54 of #100DaysOfLeetCode 🔍 Problem Summary: Given an unsorted integer array nums, return the smallest positive integer that is missing. You must solve it in O(n) time and O(1) extra space. This is one of the most elegant and clever array manipulation problems. 🧠 Intuition: Key observations: The answer must be in the range [1, n+1] We want each number x (1 ≤ x ≤ n) to be placed at index x - 1 This leads to the index marking / cyclic placement trick: Iterate through the array Place each number x into its correct position: At index x - 1 By swapping until the number is either out of range or already in correct place After rearrangement, the first index i where nums[i] != i + 1 gives the answer If all numbers are in correct places → answer is n + 1 Simple idea, extremely powerful.⚙️ Performance: ⏱️ Runtime: 2 ms 🚀 💪 Beats: 99.8% of Java solutions 💾 Memory: 56 MB ⚡ (Beats 95% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ✨ Key Takeaway: This problem teaches the Cyclic Sort pattern — an essential technique for problems involving: Missing numbers Duplicates Correct placement In-place array rearrangement Mastering this trick gives you an edge in advanced array manipulation question Link:[https://lnkd.in/gV8y8dhc] #100DaysOfLeetCode #Day54 #Problem41 #FirstMissingPositive #CyclicSort #IndexMapping #Algorithms #DSA #Java #LeetCode #ProblemSolving #CodingChallenge #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #CodingCommunity #DataStructures #DeveloperJourney #ArjunInfoSolution #TechCareers #CareerGrowth #Programming #CodeNewbie #ComputerScience #LearnToCode #ZeroToHero #CodingIsFun #CodeLife #JavaDeveloper #GameDeveloper #Unity #AI #MachineLearning
To view or add a comment, sign in
-
-
🚩 Problem: 78. Subsets 🔥 Day 56 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums, return all possible subsets (the power set). The solution set must not contain duplicates, and the order does not matter. 🧠 Intuition: This is one of the simplest and cleanest backtracking problems. At each index, you have only two choices: Include the current element Exclude the current element This naturally builds the entire power set. Alternatively, you can also build subsets by expanding a list from left to right. ✅ Backtracking Approach: Start with an empty subset Recursively explore adding each number After each choice, backtrack and remove it Add all generated combinations into the result Super clean and beginner-friendly. ⚙️ Performance: ⏱️ Runtime: 1 ms 🚀 💪 Beats: 97% of Java solutions 💾 Memory: 43 MB ⚡ (Beats ~90% of users) 📊 Complexity: Time Complexity: O(n × 2ᶰ) Space Complexity: O(n) (recursion + temp list) ✨ Key Takeaway: This problem teaches the classic recursive structure used for: Subsets Combinations Nested choices Decision-tree exploration It's the perfect stepping stone to more advanced backtracking problems. Link:[https://lnkd.in/gfQV_8w4] #100DaysOfLeetCode #Day56 #Problem78 #Subsets #Backtracking #Recursion #Algorithms #DSA #Java #ProblemSolving #LeetCode #CodingChallenge #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #ArjunInfoSolution #DeveloperJourney #LearnToCode #TechCareers #CareerGrowth #CodeNewbie #ZeroToHero #CodingIsFun #JavaDeveloper #GameDeveloper #Unity #AI #MachineLearning
To view or add a comment, sign in
-
-
👉 LeetCode 367: Valid Perfect Square. Binary search problem - this time to check if a number is a perfect square without using any built-in square root function. 👇 Here’s my implementation: class Solution { public boolean isPerfectSquare(int num) { if(num == 1){ return true; } int left = 1, right = num/2; while(left<=right){ int mid = left + (right-left)/2; if(mid == num/mid && num%mid == 0){ return true; }else if(mid < num/mid){ left = mid + 1; }else{ right = mid - 1; } } return false; } } 👉 Step-by-step logic: 1. Handle the edge case when num is 1. 2. Use binary search between 1 and num/2. 3. Calculate mid, then check if mid * mid == num. .To avoid overflow, the code uses num/mid instead of mid * mid. 4. If it matches perfectly and num % mid == 0, return true. 5. Adjust search boundaries accordingly until you find it or exhaust all options. 👉 Time Complexity:O(log n) — binary search halves the range each time. 👉 Space Complexity:O(1) — only a few integer variables are used. #LeetCode #Java #ProblemSolving #BinarySearch #Coding
To view or add a comment, sign in
-
🔥 Day 35/100 of #100DaysOfCode - Finding Longest Sequence! Today's Problem: Longest Consecutive Sequence Task: Find the length of the longest consecutive elements sequence in an unsorted array. Solution: Used a HashSet for O(1) lookups! First added all elements to the set, then for each number, checked if it's the start of a sequence (no num-1 in set). If yes, counted consecutive numbers ahead. Key Insights: O(n) time complexity by only checking sequence starters HashSet eliminates duplicates and provides fast lookups Avoids O(n log n) sorting approach Smart Optimization: Only begins counting from sequence starting points Each number is processed at most twice (visited in set iteration + sequence counting) Handles duplicates and empty arrays gracefully Elegant solution that transforms an O(n²) brute force into O(n) using smart data structure choice! 💡 #100DaysOfCode #LeetCode #Java #Algorithms #HashSet #Arrays #CodingInterview
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