📌 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 🚀
Solved LeetCode #19: Remove Nth Node from End of List
More Relevant Posts
-
🚀 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
-
-
📌 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 🚀
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
-
-
Don’t dive into LeetCode before you know this. It can save 40% of your time… 👇 I wasted weeks because I didn’t know this. What changed? 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱 𝗖++ 𝗦𝗧𝗟 (𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝗯𝗿𝗮𝗿𝘆). 🧠 Why it matters: STL saves you from writing complex data structures from scratch. Everything — from sorting to searching — is already optimized and tested. 𝗜𝘁 𝗵𝗮𝘀 𝟰 𝗺𝗮𝗶𝗻 𝗽𝗮𝗿𝘁𝘀: ➝ Containers (the data structures) ➝ Algorithms (the actions, like sort()) ➝ Iterators (the “pointers” that move through them) ➝ Functions (we’ll skip this for now) ⚡ 𝗟𝗲𝘁’𝘀 𝗱𝗶𝘃𝗲 𝗶𝗻𝘁𝗼 𝗖𝗼𝗻𝘁𝗮𝗶𝗻𝗲𝗿𝘀 — 𝗠𝗼𝘀𝘁 𝗨𝘀𝗲𝗱 (𝗶𝗻 𝗼𝗿𝗱𝗲𝗿): ➝ vector – dynamic array, most common → vector<int> v = {1,2,3}; ➝ unordered_map – fastest key-value lookups → unordered_map<string,int> mp; ➝ map – sorted key-value pairs ➝ set – unique sorted elements ➝ unordered_set – unique, unsorted, faster ➝ deque – insert/remove from both ends ➝ list – doubly linked list ➝ stack / queue / priority_queue – specific use (LIFO/FIFO) ➝ array – fixed size, static 💡 𝗤𝘂𝗶𝗰𝗸 𝗧𝗶𝗽𝘀: ➝ Use vector by default unless you have a reason not to. ➝ Use unordered_map when you need speed, map when you need order. ➝ set and unordered_set are perfect for unique elements. 📌 Save this post — you’ll need it every time you start a DSA problem 🚀 #cplusplus #stl #dsa #programming #codingjourney #developers #techstudents #leetcode #students #engineeringlife #competitiveprogramming
To view or add a comment, sign in
-
-
LeetCode 217: Contains duplicate ⁇ Suppose you have a list of numbers, and you want to know if any number appears more than once. It’s like making sure everyone in class has a unique roll number! Approach 1: Set - Go through each number. - If it’s not in your set, add it. - If you ever see a number already in your set, you’ve got a duplicate! Approach 2: Hash Table (Counter) - Use a Counter to count how often each number appears in the list. - If any number appears more than once, return True (there’s a duplicate). Complexity: - Time Complexity: O(n) — One pass through all numbers. - Space Complexity: O(n) — Storing seen numbers or counts. Both approaches are fast and effective for catching duplicates quickly! Let’s check our numbers and make sure everyone’s unique! Check out the problem here: https://lnkd.in/g-JgRTEn Keep going, keep revising, and keep building confidence! 💪🔥 #DSA #Coding #ProblemSolving #Learning
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 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
-
-
Today, I revisited one of my favorite algorithmic challenges: searching in a rotated sorted array — but this time, with duplicates allowed. 🧩 The key challenge? When duplicates appear (like [1,0,1,1,1]), traditional binary search fails to clearly identify which half is sorted. The trick is to handle this uncertainty by shrinking the search space when both ends are equal: if (nums[s] == nums[mid] && nums[mid] == nums[e]) { s++; e--; } This small but smart adjustment ensures the algorithm stays as close to O(log n) as possible, even when duplicates make things messy. 💡 Takeaway: Sometimes in problem-solving — and even in real-world coding — progress isn’t about big leaps, but about small, clever optimizations that make your approach robust in every scenario. #Coding #DSA #ProblemSolving #Cplusplus #LearningJourney #LeetCode #SoftwareEngineering
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
-
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