LeetCode 41 – First Missing Positive. 🧩 When I first read this problem, I thought it would be messy. But once I found the pattern, it turned out to be surprisingly clean. The problem in simple terms: Find the smallest positive integer missing from an unsorted array. The real challenge: O(n) time and O(1) extra space. No sorting, no hash maps, no extra arrays. At first, that feels impossible. But here's the trick that clicked for me: The answer has to be between 1 and n+1 (where n = length of array). Why? Because in the best case, if the array contains 1,2,3,...,n, then the missing number is n+1. Otherwise, there's a gap somewhere between 1 and n. Once I realized that, the solution became straightforward: Place each number in its correct position (number x should be at index x-1) | After rearranging, scan to find the first spot where the number doesn't match the index + 1 That index + 1 is our answer What I liked about this problem: It teaches you to work within tight constraints. Instead of adding more memory, you use the array itself as your workspace. If you're preparing for coding interviews, this is one of those problems worth understanding deeply, not for memorizing the solution but for learning how to think under constraints. Have you run into a problem that looked impossible but turned out to have a simple pattern? Curious to hear your experience. #LeetCode #CodingInterview #ProblemSolving #Java #Algorithms
First Missing Positive Integer in Unsorted Array
More Relevant Posts
-
🚀 LeetCode Problem of the Day 📌 Problem: Minimum Distance to Target Element Given an integer array nums (0-indexed) and two integers target and start, we need to find an index i such that: nums[i] == target |i - start| is minimized 👉 Return the minimum absolute distance. 💡 Key Idea: We simply scan the array and track the minimum distance whenever we find the target. 🧠 Approach Traverse the array Whenever nums[i] == target, compute abs(i - start) Keep updating the minimum result 💻 Java Solution class Solution { public int getMinDistance(int[] nums, int target, int start) { int res = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { res = Math.min(res, Math.abs(i - start)); } } return res; } } 📊 Complexity Analysis ⏱ Time Complexity: O(n) → single pass through the array 🧠 Space Complexity: O(1) → no extra space used ⚡ Simple linear scan, optimal solution — sometimes brute force is already the best solution! #LeetCode #Coding #Java #ProblemSolving #DataStructures #Algorithms #InterviewPrep
To view or add a comment, sign in
-
-
**Day 104 of #365DaysOfLeetCode Challenge** Today’s problem: **String Compression (LeetCode 443)** A classic **Two Pointer + In-place manipulation** problem that tests how efficiently you can work with arrays without extra space. 💡 **Core Idea:** We compress the string by grouping **consecutive repeating characters**: * If count = 1 → just write the character * If count > 1 → write character + count 👉 And the catch? Do everything **in-place (O(1) extra space)** 📌 **Approach:** * Use two pointers: * `i` → to traverse the array * `index` → to write compressed result * Count consecutive characters * Write character and its frequency (if >1) * Convert count to string and insert digit by digit ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(1) **What I learned today:** In-place problems are all about **careful pointer management**. 💭 **Key Takeaway:** When asked to modify arrays without extra space: 👉 Think **read pointer + write pointer** These small optimizations make a huge difference in interviews #LeetCode #DSA #TwoPointers #Strings #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
📅 Date: April 27, 2026 Day 6 of my LeetCode Journey 🚀 ✅ Problem Solved: 15. 3Sum 🧠 Approach & Smart Solution: This classic medium-level problem is a great test of optimizing loops! A brute-force O(n³) approach would easily hit a Time Limit Exceeded (TLE). Instead, I optimized it to O(n²) using the Sorting + Two-Pointer technique. • Pseudo-code: First, sort the given array. Iterate through the array with an index 'i'. Skip duplicate elements to avoid duplicate triplets. Set two pointers: 'j' right after 'i', and 'k' at the end of the array. While 'j' is less than 'k': Calculate the sum of elements at i, j, and k. If the sum is 0, we found a valid triplet! Add it to the result list, and smoothly skip any duplicate values for both 'j' and 'k'. If the sum is less than 0, increment 'j' to increase the sum. If the sum is greater than 0, decrement 'k' to decrease the sum. By sorting first, we can systematically eliminate duplicate triplets and efficiently navigate towards the target sum without redundant checks! ⏱️ Time Complexity: O(n²) (Sorting takes O(n log n), and the two-pointer search takes O(n²)) 📦 Space Complexity: O(1) (Auxiliary space, excluding the space required for the output list) 📊 Progress Update: • Streak: 6 Days 🔥 • Difficulty: Medium • Pattern: Two Pointers / Sorting 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering the two-pointer technique on sorted arrays is a massive level-up for optimizing complex algorithms! 💡 #LeetCode #DSA #TwoPointers #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Day 33 of My DSA Journey – Reverse Vowels of a String (LeetCode) Today I worked on a really interesting problem: Reverse Vowels of a String — and learned how powerful the two-pointer approach can be. 🔍 Problem Understanding We are given a string, and we need to reverse only the vowels while keeping the rest of the characters in the same position. 👉 Example: Input: "hello" Output: "holle" 🐢 Brute Force Approach Extract all vowels into a separate list Reverse that list Traverse the string again and replace vowels one by one ⛔ Time Complexity: O(n) ⛔ Space Complexity: O(n) (extra storage used) ⚡ Optimized Approach (Two Pointer) Instead of extra space, I used two pointers (i, j): Steps: Initialize: i = 0 (start) j = n-1 (end) Move i forward until it finds a vowel Move j backward until it finds a vowel Swap both vowels Repeat until i < j 🧠 Example Walkthrough Input: "leetcode" i → 'e', j → 'e' → swap i → 'e', j → 'o' → swap Final Output: "leotcede" ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ (in-place) 💡 Key Learning Two-pointer approach is extremely useful for string manipulation problems Always try to reduce extra space usage Clean condition handling (like checking vowels) matters a lot in interviews 🙏 Thanks to LeetCode for such great problems that strengthen problem-solving skills. 📈 Consistency is the key — small steps daily lead to big results. #DSA #Java #LeetCode #ProblemSolving #CodingJourney #100DaysOfCode #InterviewPreparation #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Just solved the Contains Duplicate problem with a fresh perspective! Instead of going with the traditional sorting + two pointer approach, I used the property of Set (uniqueness) to achieve an O(n) time complexity solution. 💡 Approach: - Traverse the array once - Use a HashSet to track elements - If an element already exists → duplicate found ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 🔁 On the other hand, the sorting + two pointer approach gives: - Time: O(n log n) - Space: O(1) 👉 So it’s a classic trade-off: - Optimize time → use Set - Optimize space → use Sorting+two pointer Really enjoyed breaking down this problem and comparing approaches — small problems like this build strong intuition for bigger ones 💪 #DataStructures #Algorithms #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 31 of #LeetCode Challenge 🔍 Problem: Decode the Slanted Ciphertext Today’s problem was all about understanding patterns and matrix traversal in a clever way! 💡 Key Idea: * The encoded string is formed by writing characters in a matrix row-wise * The trick is to read diagonally (↘️ direction) to decode the original message * No need to build a 2D matrix — we can directly calculate indices! 🧠 What I Learned: * How to convert 1D string into virtual 2D matrix * Diagonal traversal techniques * Importance of trimming trailing spaces in string problems ⚡️ Approach: * Calculate number of columns → cols = n / rows * Traverse diagonally from each column * Append characters using index formula i * cols + j * Remove extra spaces at the end 💻 Language: Java 🎯 Time Complexity: O(n) 📦 Space Complexity: O(n) Consistency is the key 🔑 — one problem at a time, getting better every day! #Day31 #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Solved “Search Insert Position” using Binary Search on LeetCode! Today I worked on an interesting problem where the goal is to find the index of a target element in a sorted array. If the target is not present, we return the index where it should be inserted to maintain sorted order. 🔍 Approach: Instead of using a linear search (O(n)), I implemented an efficient Binary Search (O(log n)) approach. 💡 Key Learning: One important detail is calculating the middle index safely: mid = low + (high - low) / 2 This avoids potential integer overflow compared to (low + high) / 2 and ensures correct behavior even for large inputs. ⚙️ Logic: If target == arr[mid] → return mid If target > arr[mid] → search right half Else → search left half If not found → return ‘low’ as the correct insert position 📈 Result: Achieved 100% performance on LeetCode 🚀 This problem reinforced my understanding of: ✔ Binary Search fundamentals ✔ Edge case handling ✔ Writing optimized and safe code Looking forward to solving more problems and improving problem-solving skills! #LeetCode #BinarySearch #Java #DataStructures #Coding #ProblemSolving
To view or add a comment, sign in
-
-
**Day 110 of #365DaysOfLeetCode Challenge** Today’s problem: **Add Two Numbers II (LeetCode 445)** A very elegant **Linked List + Stack** problem. We are given two numbers stored in linked lists where the **most significant digit comes first**. Example: `7243 + 564 = 7807` Lists: `[7,2,4,3] + [5,6,4] = [7,8,0,7]` 💡 **Core Challenge:** Normally addition starts from the **last digit**… But linked lists are given from the **front**. So how do we add from right to left **without reversing the lists**? 📌 **Approach:** 1️⃣ Push digits of both linked lists into stacks 2️⃣ Pop from stacks → gives digits from right to left 3️⃣ Add with carry 4️⃣ Insert new node at the front of result list This preserves correct order naturally ⚡ **Time Complexity:** O(n + m) ⚡ **Space Complexity:** O(n + m) **What I learned today:** Stacks are incredibly useful when you need to process data in **reverse order**. 💭 **Key Takeaway:** If you can’t move backward easily: 👉 Use a stack 👉 Simulate reverse traversal 👉 Build result from front Clean solution. Smart idea. Great interview problem #LeetCode #DSA #LinkedList #Stack #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Dynamic Programming used to give me absolute nightmares. Now? It’s my favorite pattern to code. 💡 Most developers fail tech interviews because they try to jump straight to the most optimized, bottom-up DP solution. That is a massive mistake. You have to understand the evolution of the problem. I spent time this week mapping out DP Pattern 1 (The Fibonacci Sequence, Climbing Stairs, and House Robber) completely by hand. I didn't just write the Java code. I broke down the exact mental framework to master these problems: 1️⃣ Recursion: The intuitive, brute-force approach (and why it causes Time Limit Exceeded). 2️⃣ Memoization (Top-Down): Adding a cache to remember past calculations and save the day. 3️⃣ Tabulation (Bottom-Up): The ultimate optimization—ditching the recursion stack entirely for a clean iterative approach. I’ve attached a few pages of my handwritten notes below. Seeing it drawn out visually makes the transition click instantly. 🧠 If you are preparing for coding interviews or just want to finally conquer Dynamic Programming, you need to master this core pattern first. I scanned all of my handwritten notes into a high-res PDF. Drop a "DP" in the comments below, and I will DM you the complete guide for free! 👇 (Make sure we are connected so I can send the message!) #SoftwareEngineering #DynamicProgramming #Java #CodingInterviews #LeetCode #DataStructures #Algorithms #TechCareers #LearnToCode
To view or add a comment, sign in
-
Today I solved the problem: "Closest Target in Circular Array" 🔍 Problem Statement: Given an array of words and a starting index, find the shortest distance to a target word in a circular array. 💡 Key Idea: Since the array is circular, we must consider: ➡️ Direct distance ➡️ Circular distance 👉 Final distance = min(|i - startIndex|, n - |i - startIndex|) 🧑💻 My Optimized Java Solution: class Solution { public int closestTarget(String[] words, String target, int startIndex) { int n = words.length; int minDistance = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (words[i].equals(target)) { int dist = Math.abs(i - startIndex); int circularDist = Math.min(dist, n - dist); minDistance = Math.min(minDistance, circularDist); } } return minDistance == Integer.MAX_VALUE ? -1 : minDistance; } } 📈 What I Learned: How to handle circular array problems 🔄 Importance of optimizing brute-force solutions Writing clean and efficient code for interviews 🔥 Consistency is the key — one problem at a time! #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode #DSA
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