Day#3 🚀 Solved: LeetCode 408 – Valid Word Abbreviation | Two-Pointer Approach Sometimes even a small string problem teaches big lessons about careful parsing and pointer logic. 🔹 Problem: Given a word and its abbreviation, determine if the abbreviation is valid. Example: word = "internationalization", abbr = "i12iz4n" → True Rules: • Numbers in the abbreviation indicate how many characters are skipped • Leading zeros are not allowed • Letters must match exactly 💡 Key Idea – Two Pointers • Use i for the word and j for the abbreviation • Traverse the abbreviation: If it’s a letter, it must match the word at i If it’s a number, convert it to an integer and skip that many characters Reject numbers with leading zeros • Valid if both pointers reach the end of their strings ⏱️ Complexity: • Time: O(n + m) • Space: O(1) 🧠 What I learned: Two-pointer techniques are versatile for string pattern problems Edge cases matter: leading zeros, empty strings, or mismatched characters Parsing and skipping carefully is often cleaner than building intermediate strings 🔁 Revisiting these “medium” problems strengthens fundamentals and highlights reusable patterns for larger system challenges. #LeetCode #SoftwareEngineering #CodingInterview #Algorithms #DataStructures #ProblemSolving #SDE
LeetCode 408: Valid Word Abbreviation Two-Pointer Approach
More Relevant Posts
-
Day#16 🚀 Solved: LeetCode 186 – Reverse Words in a String II | In-Place Two-Pointer: A great follow-up to the classic reverse words problem — but with a twist: 🔹 Problem: Given a character array s, reverse the order of words in-place. 👉 No extra array allowed 👉 Words are separated by single spaces 👉 Input is a char array, not a string 💡 Key Intuition – Reverse Twice “Reverse the whole string, then reverse each word.” 🔄 Process: Reverse entire array Traverse and identify each word Reverse each word individually 🔹 Pseudo Code: function reverseWords(s): reverse(s, 0, n-1) start = 0 for i from 0 to n: if i == n or s[i] == ' ': reverse(s, start, i-1) start = i + 1 🔍 Example: Input: ["t","h","e"," ","s","k","y"] Step 1 → Reverse whole array 👉 "yks eht" Step 2 → Reverse each word 👉 "sky the" 💡 Why this works: • First reversal fixes word order • Second reversal fixes character order • No extra memory needed ⏱️ Complexity: • Time → O(n) • Space → O(1) ✅ 📌 Why Two Pointers? • Needed to reverse segments efficiently • Avoids extra memory usage • Enables in-place transformation 🧠 What I learned: • In-place problems require thinking in transformations • Two-pointer technique is extremely powerful for arrays/strings • Breaking problems into steps simplifies complex constraints • Small variations in problems can change the entire approach 🔁 Key takeaway: 👉 “Reverse globally, then fix locally.” #LeetCode #Strings #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
🚀 Binary Search | Clean Thinking > Complex Code Just solved the classic Binary Search LeetCode Problem 704 with 100% test cases passing and optimal runtime. Here’s a structured breakdown of my approach 👇 🎯 Problem Goal Find the index of a target element in a sorted array using an efficient approach. 🧠 My Approach 1. Define the Search Space → Initialize low = 0, high = n - 1 2. Apply Binary Search Logic → Compute mid → Compare target with nums[mid] → Eliminate half of the search space each step 3. Maintain Clean Boundaries → Move low or high precisely to avoid infinite loops 4. Exit Condition → Return index if found → Else return -1 ⚡ What I Focused On • Writing minimal, readable code • Avoiding unnecessary conditions • Staying calm and methodical • Trusting fundamentals over shortcuts 💡 Key Takeaway Strong fundamentals + structured thinking = fast and reliable problem solving 📈 Outcome ✔️ 100% test cases passed ✔️ Optimal time complexity: O(log n) ✔️ Clean execution without overthinking Building this discipline every day. Small wins → Big growth 💪 #BinarySearch #DataStructures #ProblemSolving #LeetCode #CodingJourney #TechGrowth #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
Day 97/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 456 – 132 Pattern(Medium) 🧠 Approach: Traverse the array from right to left while maintaining a stack. Use a variable to track the “middle” element (the ‘2’ in 132 pattern) and check if a valid pattern exists. 💻 Solution: class Solution: def find132pattern(self, nums: List[int]) -> bool: stack = [] third = float('-inf') for i in range(len(nums) - 1, -1, -1): if nums[i] < third: return True while stack and nums[i] > stack[-1]: third = stack.pop() stack.append(nums[i]) return False ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Using a monotonic stack while iterating backwards helps efficiently detect complex patterns in linear time. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
Day#18 🚀 Solved: LeetCode 141 – Linked List Cycle | Fast & Slow Pointer Detecting cycles in a linked list is a classic problem — elegantly solved with two pointers: 👉 Must detect without modifying the list and ideally in O(1) space 🔹 Problem: Given the head of a singly linked list, determine if the list has a cycle. Return true if a cycle exists, else false Cannot modify the nodes 💡 Key Intuition – Fast & Slow Pointer (Floyd’s Tortoise & Hare) “Move one pointer twice as fast as the other. If a cycle exists, fast will eventually meet slow.” 🔄 Process: Initialize slow = head, fast = head Move slow 1 step at a time Move fast 2 steps at a time If fast meets slow → cycle exists If fast reaches null → no cycle 🔹 Pseudo Code: function hasCycle(head): slow = head fast = head while fast != null AND fast.next != null: slow = slow.next fast = fast.next.next if slow == fast: return true return false 🔍 Example: Input: 3 → 2 → 0 → -4 → back to 2 slow moves 1 step, fast moves 2 steps After a few iterations → slow = fast → cycle detected ✅ Input: 1 → 2 → 3 → null fast reaches null → no cycle ❌ 💡 Why this works: • Fast moves 2× → if there’s a cycle, it will eventually lap slow • Constant space → O(1) • Elegant and deterministic solution ⏱️ Complexity: • Time → O(n) ✅ • Space → O(1) ✅ 📌 Why Two Pointers? • Perfect for linked lists & sequences • Avoids extra memory like hash sets • Detects cycles in one pass 🧠 What I learned: • Fast & slow pointer technique is generalizable to other sequence problems (like Happy Numbers) • Key idea: difference in speeds ensures meeting inside cycles • Elegant solutions often combine simple pointers + math reasoning 🔁 Key takeaway: 👉 “Move fast, detect slow — cycles cannot hide.” #LeetCode #LinkedList #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
🚀 Day 4 — Reverse Integer Continuing my journey of improving problem-solving skills with consistency and discipline — one problem every day. Today’s challenge was not just about reversing digits, but handling constraints smartly. 🧩 Problem Solved: • Reverse Integer (LeetCode #7) 📚 Topic: Math + Edge Case Handling 💡 Key Insight: Reversing a number is easy — but ensuring the result stays within the 32-bit integer range is the real challenge. ⚡ Approach: • Identify the sign of the number • Convert number to absolute value • Extract digits using % 10 • Build reversed number step by step • Check for overflow before updating • Reapply the original sign 🎯 Takeaway: Writing code that works is good — writing code that handles edge cases is better. ⏱ Complexity: • Time → O(log n) • Space → O(1) 💻 Example: Input → 123 → Output → 321 Input → -123 → Output → -321 Input → 120 → Output → 21 Consistency builds confidence 🚀 #ProblemSolving #LeetCode #CodingJourney #100DaysOfCode #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
Moving Beyond Brute Force: Optimizing Sum of Distances 🚀 In software engineering, writing code that works is only the first step. Writing code that scales is where the real challenge lies. I recently tackled LeetCode 2615 (Sum of Distances), and it’s a perfect example of why understanding time complexity is crucial for a developer. The Problem: Given an array, for each element, calculate the sum of absolute differences ∣i−j∣ ∣i−j∣ for all other indices j j where the values are identical.The Developer’s Approach: 1️⃣ Identify the Bottleneck: A naive nested loop ( O(n2) O(n2 ) ) would attempt billions of operations for an input size of 105 105 , leading to a Time Limit Exceeded (TLE) error. We need an O(n) O(n) solution.2️⃣ Data Grouping: Use a HashMap to group indices of the same value. This narrows our focus only to relevant elements. 3️⃣ The Math Pivot (Prefix Sums): Instead of re-calculating distances for every index, we use mathematics. The total distance for any index can be split into: Left Side: (count_of_elements_on_left * current_index) - (sum_of_left_indices) Right Side: (sum_of_right_indices) - (count_of_elements_on_right * current_index) The Result: By maintaining a running prefix sum while iterating through the grouped indices, we transform a complex quadratic problem into a linear one. Key Takeaway: When you see "sum of absolute differences" in an array, think Prefix Sums. It’s one of the most powerful tools in a developer’s arsenal to turn inefficient logic into high-performance code. How do you approach optimization when you hit a performance wall? Let’s discuss in the comments! 💻✨ #SoftwareEngineering #Coding #Algorithms #Optimization #LeetCode #ProblemSolving #DeveloperMindset #CleanCode
To view or add a comment, sign in
-
🚀 Day 97 of 100 Days of DSA 📌 LeetCode #96 (Unique Binary Search Trees) 📈 "Consistency over motivation, Progress over perfection" A classic Dynamic Programming problem that introduces the concept of Catalan Numbers. 🧩 Problem Statement Given an integer n: Count the number of structurally unique BSTs that can be formed using values from 1 to n 🧠 Thought Process At first: Try constructing all possible BSTs But quickly: - Number of trees grows rapidly - Explicit construction becomes inefficient So the focus shifts to: Counting instead of constructing 🚫 Brute Force Approach 1. Try all possible ways to build BSTs 2. For each root: • Recursively build left and right subtrees Problems: • Repeated subproblems • Huge recursion tree Time Complexity → Exponential ❌ 🔍 Key Insight Pick any number i as root: Left subtree → values [1 … i-1] Right subtree → values [i+1 … n] Number of BSTs: left_subtrees × right_subtrees 💡 Recurrence Relation Let: dp[n] = number of unique BSTs with n nodes Then: For each root i: dp[n] += dp[i - 1] * dp[n - i] ✅ Approach Used Dynamic Programming (Catalan Pattern) ⚙️ Strategy 1. Base cases: • dp[0] = 1 (empty tree) • dp[1] = 1 2. For each number of nodes: • Try every possible root • Combine left & right subtree counts 3. Build solution bottom-up 💡 Intuition Instead of building trees: Count how many ways left and right can be formed Then combine them. This transforms a structural problem into a counting problem. ⏱ Complexity Analysis Time Complexity: O(n²) Space Complexity: O(n) 💡 Key Learnings - Breaking problem into left & right subtrees simplifies logic - Recursive problems often hide DP patterns - This is a classic example of Catalan numbers - Counting problems are often easier than constructing solutions #100DaysOfDSA #Day97 #LeetCode #DynamicProgramming #BST #Catalan #Algorithms #DSA #CodingJourney
To view or add a comment, sign in
-
-
I memorized the for loop syntax five times before it finally clicked. for (let i = 0; i < array.length; i++) {} The problem wasn't memory — it was that I didn't understand what I was saying. Once I translated it to plain English, everything changed: → Let i start at 0 → Keep going as long as i is less than the array's length → After each loop, add 1 to i → Run this block of code each time Now I use loops constantly. Print every item in a list. Find the max number. Filter out values. Sum an array. These aren't abstract exercises — they're patterns I've used in real projects. Understanding loops deeply means you can solve problems you've never seen before. That's the difference between a developer and someone who copies Stack Overflow. What was the concept that finally unlocked your ability to think programmatically?
To view or add a comment, sign in
-
-
LeetCode Daily | Day 81 🔥 LeetCode POTD – 2452. Words Within Two Edits of Dictionary (Medium) ✨ 📌 Problem Insight Given two arrays of same-length words: ✔ queries and dictionary ✔ You can change characters (edits) in a query ✔ Match if ≤ 2 edits needed ✔ Return all such queries 🔍 Initial Thinking – Brute Force ⚙️ 💡 Idea: ✔ Compare every query with every dictionary word ✔ Count character differences ⚠️ Concern: ✔ Seems heavy → O(Q × D × n) ✔ But constraints are small → acceptable 💡 Key Observation 🔥 ✔ This is just Hamming Distance ≤ 2 ✔ Early stopping helps → stop once diff > 2 ✔ No need for complex data structures 🚀 Optimized Approach ✔ For each query: → Compare with dictionary words → Count mismatches → If mismatches ≤ 2 → valid 🔧 Core Idea ✔ Character-by-character comparison ✔ Break early if differences exceed 2 ✔ Add query once a match is found ⏱ Complexity ✔ Time: O(Q × D × n) ✔ Space: O(1) 🧠 Key Learning ✔ Not every problem needs optimization tricks ✔ Constraints guide the approach ✔ Early breaking can significantly reduce runtime 🚀 Takeaway A clean implementation problem where recognizing Hamming distance makes everything straightforward ⚡ #LeetCode #DSA #Algorithms #CPlusPlus #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
📌 Strengthening DSA Concepts through Problem Solving Recently, I worked on LeetCode 525 – Contiguous Array At first glance, it looks like a simple array problem… but the real challenge? Converting it into a prefix sum problem and spotting patterns 🔍 Problem You’re given: 👉 nums → a binary array (only 0s and 1s) Your task: 👉 Find the maximum length of a contiguous subarray with equal number of 0s and 1s 🧠 Naive Thinking → Generate all subarrays → Count 0s and 1s in each But this leads to: ❌ Time complexity ~ O(n²) ❌ Not efficient for large inputs 💡 Optimized Approach (Prefix Sum + HashMap) 👉 Convert the problem cleverly: Treat 0 as -1 Treat 1 as +1 Now the problem becomes: 👉 Find the longest subarray with sum = 0 🔑 Key Idea 1️⃣ Maintain a running sum 2️⃣ Store the first occurrence of each sum in a HashMap 3️⃣ If the same sum appears again → subarray in between has sum = 0 4️⃣ Track the maximum length 👉 Why first occurrence? Because it gives the longest possible subarray ⚙️ Core Logic 👉 If sum is seen before at index j 👉 Current index is i Then: 👉 subarray length = i - j 🚀 Why this works 👉 Equal 0s and 1s cancel each other out 👉 Same prefix sum means net effect is zero 👉 Efficiently avoids recomputation ⏱️ Complexity 👉 Time Complexity: O(n) 👉 Space Complexity: O(n) #DSA #PrefixSum #HashMap #LeetCode #ProblemSolving #CodingInterview #100DaysOfCode
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