📌 Day 34/150 – Letter Combinations of a Phone Number (LeetCode #17) Today’s problem was a creative mix of recursion and backtracking, simulating how old phone keypads map digits to letters. ☎️ The challenge? Given a string of digits (2–9), generate all possible letter combinations that the digits could represent. At first, it looks like a simple mapping problem — just convert digits to letters. But the real task is to explore every possible combination of those letters in a systematic way. 🔹 Brute Force Idea Try every combination by using nested loops for each digit. ✅ Works for small inputs. ❌ Fails as the number of digits increases — leads to exponential growth in possibilities. 🔹 Optimal Approach – Backtracking (DFS) 👉 Key Insight: Treat each digit as a node and explore all possible letter choices for it recursively. Build combinations character by character until all digits are processed. At each step: Pick one letter from the current digit’s mapping. Recurse for the next digit. Backtrack to explore other possibilities. This ensures we cover all possible combinations efficiently and elegantly. 🧠 Example: Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] Here’s how it works: 2 → "abc" 3 → "def" We combine every letter from "abc" with every letter from "def". ⏱️ Time Complexity: O(3ⁿ × 4ᵐ) (since 7 & 9 have 4 letters each) 📦 Space Complexity: O(n) (recursion depth) 💡 Learning: Backtracking problems often feel complex, but they’re just structured explorations of possibilities. Once you visualize recursion as a decision tree, these problems become much easier to reason about. 🌳 #150DaysOfCode #LeetCode #ProblemSolving #Backtracking #Recursion #DSA #CodingChallenge #SoftwareEngineering #Cplusplus #Developers #LearningJourney #TechCommunity 🚀
Solving LeetCode #17: Phone Number Letter Combinations with Backtracking
More Relevant Posts
-
🚀 Day 93 of #100DaysOfLeetCode — Minimum Operations to Convert All Elements to Zero (Leetcode 3542) Today’s problem was a fun one that really tests your understanding of array manipulation and pattern observation! 🧩 Problem: Given an array of non-negative integers, the goal is to find the minimum number of operations needed to make all elements 0. In each operation, you can select a subarray and set all occurrences of the minimum non-zero element in that subarray to 0. 💭 Example: nums = [3, 1, 2, 1] ✅ Output → 3 ⚙️ Brute Force Approach: Iterate through the array and repeatedly find the smallest non-zero number. Set all its occurrences to zero. Count operations until all elements become zero. 🔹 Time Complexity: O(n²) 🔹 Space Complexity: O(1) ⚡ Optimal Approach (Used in my Solution): Use a stack-like logic or greedy approach to count how many unique increasing non-zero elements exist in the array. Each unique segment of increasing non-zero values corresponds to one operation. 🧠 Key Idea: If the next element is larger than the previous one, it represents a new operation zone. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(n) 🔍 Dry Run Example: Input: [0, 2] Skip zeros. 2 is non-zero → stack is empty → push it and increment operation count. ✅ Result = 1 💡 Key Learnings: Observing array patterns helps to reduce redundant operations. Always analyze monotonic properties for greedy optimization. Stack logic can simplify subarray-based operation problems. 🔥 Tech Used: C++ | Arrays | Stack | Greedy 🧠 Concepts: Array traversal, Greedy Reduction, Monotonic Stack #LeetCode #Day93 #100DaysOfCode #DSA #CodingChallenge #CPlusPlus #Algorithms #ProblemSolving #GreedyAlgorithm #LearningEveryday #TechWithAnurag #CodeNewbie #SoftwareEngineering #FAANGPrep
To view or add a comment, sign in
-
-
🥷 Day 164 of My 365 LeetCode Challenge is done! 💥 Kicked off strong, solved my problem, and the coding vibe is awesome! 🧠 💡 LeetCode 1625 — Lexicographically Smallest String After Applying Operations Today’s challenge was an interesting blend of string manipulation, BFS traversal, and modular arithmetic — the kind of problem that truly sharpens both your algorithmic thinking and pattern recognition skills. 🧠✨ We’re given a numeric string s and two integers a and b. Two operations can be performed repeatedly in any order: 1️⃣ Add a to all digits at odd indices (with digits wrapping around modulo 10). 2️⃣ Rotate the string to the right by b positions. The goal? 🔍 Find the lexicographically smallest string possible after performing any number of these operations. Sounds simple, right? But here’s the catch — since operations can be performed infinitely, the problem hides a state-space exploration challenge. The same string can appear multiple times via different paths, so blindly iterating could easily lead to infinite loops or redundant computations. ⚙️ Approach & Thought Process: To systematically explore all possible transformations, I used Breadth-First Search (BFS) — perfect for enumerating all reachable states in minimal steps. 🔸 Step 1: Start from the original string and push it into a queue. 🔸 Step 2: For each string, perform both allowed operations: - Add a to digits at odd indices (handling digit wraparound using (digit + a) % 10). - Rotate the string by b positions. 🔸 Step 3: Use a set to track all previously visited strings to prevent cycles. 🔸 Step 4: Continuously compare and update the smallest lexicographic string seen so far. Once the queue is exhausted, the smallest recorded string is our answer ✅ 🔥 Key Learning: This problem elegantly demonstrates how graph traversal (BFS) can be applied beyond traditional graphs — even on state transformations of strings. Recognizing this pattern is a huge step toward mastering advanced algorithmic thinking. ✨ Every problem like this one is a reminder that great coding isn’t about memorizing — it’s about seeing structure where others see chaos. #LeetCode #CPlusPlus #CodingChallenge #ProblemSolving #Algorithms #BFS #SoftwareEngineering #Programming #LearningJourney #CodeNewbie #DataStructures
To view or add a comment, sign in
-
-
🚀 Day 34 of My DSA Journey — Exploring Recursion & Backtracking 🧩 Problem 1: Generate Parentheses LeetCode #22 | Medium 🔍 Introduction: Given n pairs of parentheses, the task is to generate all possible combinations of well-formed parentheses. This problem is a classic example of backtracking, where we make decisions step-by-step and discard invalid ones along the way. 💡 Approach: We use recursion to build valid strings by keeping track of the number of open and close brackets used so far: Add '(' if open count < n. Add ')' if close count < open. Continue until both counts equal n. 🕒 Time Complexity: O(4^n / √n) (Catalan number complexity) 💾 Space Complexity: O(n) (recursion stack + temporary string) This approach ensures only valid combinations are explored, avoiding unnecessary computations. 🧩 Problem 2: Print All Subsequences / Power Set Concept: Recursion & Subset Generation 🔍 Introduction: Given an array or string, we need to generate all possible subsequences (or subsets). Each element has two choices — include or exclude — leading to a total of 2^n possible combinations. This problem strengthens the understanding of recursive decision-making and forms the base for subset-related problems. 💡 Approach: At each recursion step, choose to include or skip the current element. Continue until the end of the array/string is reached. Print or store the formed subset. 🕒 Time Complexity: O(2^n) 💾 Space Complexity: O(n) (recursion depth) 🎯 Key Takeaway: Both problems revolve around exploring all possibilities — but with different constraints: Generate Parentheses focuses on valid structured output. Power Set explores all possible outcomes. Understanding these recursive foundations is crucial before tackling advanced backtracking problems like Combination Sum, Subsets II, or Palindrome Partitioning. #Day34 #100DaysOfDSA #Backtracking #Recursion #LeetCode22 #CodingJourney #ProblemSolving #LearnWithMe #DSA
To view or add a comment, sign in
-
📌 Day 35/150 – Remove Nth Node From End of List (LeetCode #19) Today’s problem was a classic linked list challenge that tested my understanding of two-pointer techniques — a powerful pattern for solving traversal-based problems efficiently. ⚙️ The task? Given the head of a linked list, remove the n-th node from the end and return the updated list. At first glance, it seems simple — just find the node from the end and delete it. But the twist lies in doing it in a single pass for optimal performance. 🚀 🔹 Brute Force Idea Traverse the list once to count total nodes, then again to remove the (length–n)th node. ✅ Easy to implement ❌ Requires two passes → not optimal 🔹 Optimal Approach – Two Pointer Technique To achieve this in one pass, we use two pointers: fast and slow. 👉 Move the fast pointer n steps ahead. 👉 Then move both fast and slow together until fast reaches the end. 👉 The slow pointer will be just before the target node — remove it cleanly. This elegant trick ensures we traverse the list only once! 🧠 Example: Input: head = [1, 2, 3, 4, 5], n = 2 Output: [1, 2, 3, 5] Here, the 2nd node from the end (4) is removed using the one-pass logic. ⏱️ Time Complexity: O(L) 📦 Space Complexity: O(1) 💡 Learning: Linked list problems often look tricky because of pointer manipulation, but patterns like slow & fast pointers simplify them beautifully. Recognizing and reusing such patterns across problems is a major step in mastering DSA. 💪 #150DaysOfCode #LeetCode #ProblemSolving #LinkedList #TwoPointer #CodingChallenge #SoftwareEngineering #DSA #Cplusplus #Developers #TechCommunity #LearningJourney 🚀
To view or add a comment, sign in
-
-
📌 Day 36/150 – Combination Sum (LeetCode #39) Today’s problem was a beautiful example of recursion and backtracking — one of the most elegant problem-solving techniques in DSA. 💡 The challenge? Given a set of distinct integers and a target, find all unique combinations where the chosen numbers sum up to the target. Each number can be used unlimited times, making it a perfect fit for recursive exploration. 🔁 At first, it looks like a simple sum problem, but the real depth lies in exploring all valid combinations efficiently without duplicates. 🔹 Brute Force Idea Try every possible combination and check if it sums up to the target. ✅ Works for small inputs ❌ Exponential time – not scalable 🔹 Optimal Approach – Backtracking We use recursion to build combinations dynamically: 👉 Pick a number if it doesn’t exceed the target. 👉 Subtract it from the target and continue exploring. 👉 Backtrack once the path is complete (or invalid). This method ensures that all combinations are explored while avoiding unnecessary computations — a perfect blend of depth-first search and pruning. 🌱 🧠 Example: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Here, 2 + 2 + 3 = 7 ✅ 7 = 7 ✅ Both are valid combinations found via recursive backtracking. ⏱️ Time Complexity: O(2ⁿ) (since every number can be included/excluded) 📦 Space Complexity: O(target) (recursion depth) 💡 Learning: Backtracking problems train your brain to think systematically — exploring, deciding, and undoing choices. Understanding this pattern builds a strong foundation for tackling advanced problems like Combination Sum II, Subset Sum, and N-Queens. ♟️ Every recursive path teaches you that failure branches are just steps toward the correct solution. 🚀 #150DaysOfCode #LeetCode #ProblemSolving #Backtracking #Recursion #DSA #Cplusplus #CodingChallenge #SoftwareEngineering #TechCommunity #LearningJourney 💻
To view or add a comment, sign in
-
-
🚀 Day 11 of my 120 Days LeetCode Challenge! 🔹 Problem: Container With Most Water Difficulty: Medium Language Used: C++ 🧩 Problem Description: You are given an array height[] where each element represents the height of a vertical line on the x-axis. The goal is to select two lines that, together with the x-axis, form a container that can hold the maximum amount of water. The container’s area is determined by the shorter line’s height and the distance between the two lines. We need to find the pair of lines that form the largest possible area. 💡 Example: Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The maximum water area that can be contained is 49 units. 🧠 Approach Used – Two Pointer Technique: Instead of checking all possible pairs (which would take O(n²) time), I used a more efficient two-pointer approach: Start with two pointers — one at the beginning (left = 0) and one at the end (right = n-1). Calculate the area between the two lines. Keep track of the maximum area found so far. Move the pointer that points to the shorter line, since moving the taller line won’t increase the area. Continue until both pointers meet. This way, we get the answer in O(n) time with O(1) extra space. ✨ Key Takeaways: Smart pointer movement can save huge computation time. Always look for patterns that let you avoid brute-force methods. The two-pointer approach is powerful for array and interval problems. #LeetCode #Day11 #120DaysChallenge #DSA #CodingJourney #ProblemSolving #CPlusPlus #LearnToCode #Tech #Programmers
To view or add a comment, sign in
-
-
💻 Day 3 of My #120DaysOfLeetCode Challenge 🚀 🧩 Problem: Longest Substring Without Repeating Characters Difficulty: Medium | Language Used: C 🔍 What’s the Problem About? The task is to find the length of the longest substring in a given string that contains no repeating characters. For example: Input: "abcabcbb" → Output: 3 (Longest substring: "abc") Input: "pwwkew" → Output: 3 (Longest substring: "wke") Input: "bbbbb" → Output: 1 (Longest substring: "b") This problem is a classic example of how we can optimize brute force logic using sliding window and two-pointer techniques. ⚙️ Approach I Used – Sliding Window Technique Instead of checking every possible substring (which would be very slow), I used a sliding window approach with two pointers (left and right) and a frequency array to track visited characters. Here’s the step-by-step thought process: Start both pointers at the beginning of the string. Move the right pointer one step at a time, adding characters to the window. If a character repeats, move the left pointer ahead until all characters in the window are unique again. Keep track of the maximum window size during the process. This ensures each character is processed only once → giving an efficient O(n) solution. 💡 Key Takeaways Learned how two-pointer and sliding window techniques can simplify substring problems. Understood how to use frequency arrays to track duplicates efficiently. Strengthened logical reasoning and window-based problem-solving skills in C. Every new problem is an opportunity to refine logic, enhance efficiency, and get one step closer to mastering Data Structures and Algorithms. Day 3 completed ✅ | 117 more to go 💪 #LeetCode #CProgramming #DSA #ProblemSolving #CodingChallenge #100DaysOfCode #LearningJourney #SlidingWindow
To view or add a comment, sign in
-
-
🚀 How I Solved LeetCode’s Word Search Problem Without DFS or Recursion When I came across Word Search (LeetCode 79), I noticed that almost every solution used DFS and backtracking. But I wanted to solve it my own way — using index tracking and adjacency logic instead of recursion. My intuition was simple: If a word exists in the grid, every next letter must lie right next to the previous one — either up, down, left, or right. That means their coordinate difference should satisfy: abs(x1 - x2) + abs(y1 - y2) == 1. This small observation became the foundation of my entire approach. 💡 My Thought Process 1️⃣ I mapped every letter in the grid to its coordinates. 2️⃣ I started from all positions of the first letter in the word. 3️⃣ For every next letter, I checked which positions are adjacent and not already used. 4️⃣ I extended paths step by step — no recursion, only iteration. 5️⃣ If any path reached the last letter → the word exists. ⚙️ My Implementation I used a BFS-style iterative search, where each state holds: the current cell (x, y) the current index in the word and a bitmask representing already-used cells. This replaced recursion and heavy visited[][][] arrays with a compact integer mask. Each move just extended to adjacent cells if the next character matched. It handled tricky cases like "ABCB" perfectly → returned false, which even some DFS implementations fail on. ✅ Why It Worked ✔️ No recursion = no stack overflow. ✔️ Bitmask = minimal memory use. ✔️ Adjacency rule = exactly matches grid movement. ✔️ Iterative BFS = simple, efficient, and logical. 🎯 What I Learned You don’t always need to follow the standard algorithms. Sometimes, just trusting your intuition and building around your idea leads to something even better. This problem taught me that creativity and logic go hand in hand. And when you believe in your approach — it truly works. 💪 #Coding #LeetCode #ProblemSolving #Cplusplus #Innovation #DSA #Learning #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 19/50 | LeetCode Coding Challenge Today's problem: Maximum Frequency After Operations - A challenging medium-level problem that tested my optimization skills! 💡 The Challenge: Given an array and k operations, we can add values in range [-k, k] to selected indices. The goal? Maximize the frequency of any element. 🎯 Key Learnings: 1️⃣ Binary Search Optimization: Replaced O(n²) nested loops with binary search using lower_bound/upper_bound - reduced complexity from O(n²) to O(n log n) 2️⃣ Two-Pointer Technique: Implemented sliding window to efficiently find valid ranges where elements can be transformed 3️⃣ Integer Overflow Awareness: Used long long for calculations with values up to 10⁹ to prevent overflow errors 4️⃣ Multiple Strategies: Combined two approaches: Keeping existing values unchanged Transforming all elements to a new target value ⚡ The Result: ✅ 633/633 test cases passed ✅ Time complexity: O(n log n) ✅ Optimized from TLE to accepted solution 🔥 Biggest Takeaway: When you hit Time Limit Exceeded, don't give up! Analyze your bottlenecks: Identify nested loops → Consider binary search or two pointers Watch for repeated computations → Use preprocessing Always handle edge cases (overflow, boundary conditions) The journey from brute force to optimal solution taught me more than just getting it right the first time ever could. Day 19 ✅ | 31 more days to go 💪 Shishir chaurasiya and PrepInsta #100DaysOfCode #CodingChallenge #LeetCode #DSA #ProblemSolving #SoftwareEngineering #CPlusPlus #Algorithms #TechJourney #LearningInPublic
To view or add a comment, sign in
-
-
🔹 DSA Daily | Check for Balanced Parentheses (C++) Balanced parentheses problems are a classic way to test your understanding of **stacks** and **logical thinking**. Today, I solved one such problem — checking if a string of parentheses, braces, and brackets is balanced. 💡 Problem Statement: Given a string containing '(', ')', '{', '}', '[' and ']', determine if the string is **balanced**. A string is balanced if every opening bracket has a corresponding closing bracket in the correct order. Approach: I used a **stack** to keep track of opening brackets. - Push every opening bracket onto the stack. - For closing brackets, check if the top of the stack has the matching opening bracket. - If it does, pop it; otherwise, the string is unbalanced. - At the end, if the stack is empty, the string is balanced. Time Complexity: O(n) — traversing the string once Space Complexity: O(n) — for the stack This problem highlights how **stacks make bracket-matching elegant and efficient**. 🚀 #DSA #CPlusPlus #Coding #ProblemSolving #Stack #BalancedParentheses #CodeEveryday #GeeksforGeeks #LeetCode #ProgrammingJourney #DataStructures #Algorithms #InterviewPrep #CodingCommunity #LogicBuilding #EfficientCode #LearnToCode #TechJourney
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