Problem 23 : LeetCode LeetCode Problem(268) Solved: First Missing Positive (Optimal In-Place Solution) 🤯 Problem: Given an unsorted array of integers, find the smallest positive integer that is not present in the array. This must be solved in O(n) time and O(1) extra space. My Approach: I solved this challenging problem using the Cyclic Sort algorithm for an optimal in-place solution. In-Place Hashing: I iterated through the array, ensuring that every number x (where 1≤x≤n) is placed at its correct index, which is x−1. For example, the number 3 belongs at index 2. Swapping: I repeatedly swapped elements that were out of place until they met the condition or were outside the valid range [1,n]. This effectively uses the array itself as a hash map. Final Scan: After the sorting phase, a final linear scan of the array quickly identified the first index i where arr[i] is not equal to i+1. The missing positive number is then i+1. Key Achievements: Time Complexity: Achieved an O(n) time complexity with a runtime of 1 ms, beating 31.66% of other Java submissions. Space Complexity: Achieved O(1) extra space, utilizing the array in-place. Memory: The solution used 47.56 MB of memory, beating 5.17% of other submissions. Link : https://lnkd.in/dJShvfwn
Solved LeetCode Problem 268: First Missing Positive
More Relevant Posts
-
🚀 Day 47 of #100DaysOfCode – LeetCode Problem #1013: Partition Array Into Three Parts With Equal Sum 💬 Problem Summary: Given an array of integers, determine whether it can be split into three non-empty parts such that: Each part has the same sum, and The partitions appear in order (left → mid → right). Formally, we need to find indices i + 1 < j such that: sum(arr[0..i]) == sum(arr[i+1..j-1]) == sum(arr[j..end]) 🧩 Examples: Input: [0,2,1,-6,6,-7,9,1,2,0,1] Output: true ✔️ Three parts sum to 3 each. Input: [0,2,1,-6,6,7,9,-1,2,0,1] Output: false 🧠 Logic: This challenge focuses on finding equal prefix sums: 1️⃣ Compute total sum of the array. 2️⃣ If total sum is not divisible by 3 → ❌ impossible. 3️⃣ Walk through the array, accumulating values. 4️⃣ Each time a segment equals target = totalSum / 3, increase the partition count. 5️⃣ If we find 2 such partitions before the last index → array can be divided. 💻 Java Solution: class Solution { public boolean canThreePartsEqualSum(int[] arr) { int total = 0; for(int num : arr) total += num; if(total % 3 != 0) return false; int target = total / 3; int sum = 0, count = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; if(sum == target) { count++; sum = 0; if(count == 2 && i < arr.length - 1) return true; } } return false; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: A great pattern-recognition problem—once you realize that only two valid partitions are needed (the third is implied), the solution becomes clean and efficient.
To view or add a comment, sign in
-
🚀 Day 31 of #100DaysOfCode – LeetCode Problem #704: Binary Search 🧩 Problem: Given a sorted array and a target value, find the index of the target using an algorithm with O(log n) time complexity. If the target doesn’t exist, return -1. 💡 Approach: This is a classic Binary Search problem. We use two pointers (i and j) to represent the current search range. Calculate the middle index mid. If nums[mid] equals the target → return mid. If target > nums[mid] → search the right half. Else → search the left half. Repeat until the range is empty. 💻 Java Code: class Solution { public int search(int[] nums, int target) { int i = 0, j = nums.length - 1; while (i <= j) { int mid_i = i + (j - i) / 2; int mid_val = nums[mid_i]; if (target < mid_val) { j = mid_i - 1; } else if (target > mid_val) { i = mid_i + 1; } else { return mid_i; } } return -1; } } ⏱️ Complexity: Time: O(log n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) Binary Search — simple, efficient, and one of the most fundamental algorithms every developer must master.
To view or add a comment, sign in
-
🚀 Day 45 of #100DaysOfCode – LeetCode Problem #941: Valid Mountain Array 💬 Problem Summary: Given an array of integers, determine whether it forms a valid mountain shape. A valid mountain must: Strictly increase to a single peak Then strictly decrease Have at least 3 elements No plateaus allowed (no equal adjacent numbers) 🧩 Examples: Input: [0,3,2,1] Output: true Input: [3,5,5] Output: false (plateau — invalid) 🧠 Logic: A mountain has two phases: 1️⃣ Climbing up: Move from the left while each next number is greater. 2️⃣ Climbing down: Move from the right while each next number is smaller. If both pointers meet at the same peak, and the peak isn't at the edge → it's a valid mountain. 💻 Java Solution: class Solution { public boolean validMountainArray(int[] A) { if (A.length < 3) return false; int n = A.length, L = 0, R = n - 1; // Walk up while (L < n - 1 && A[L] < A[L + 1]) { L++; } // Walk down while (R > 0 && A[R] < A[R - 1]) { R--; } // Check if L and R meet at a valid peak return L == R && L != 0 && R != n - 1; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: Two-pointer strategies are incredibly powerful for problems with clear directional patterns. This one becomes simple once you think of the array as a climb + descent.
To view or add a comment, sign in
-
🚀 Day 30 of #100DaysOfCode – LeetCode Problem #88: Merge Sorted Array 🧩 Problem: You’re given two sorted arrays, nums1 and nums2, and need to merge them into a single sorted array — in-place inside nums1. The catch? You can’t return a new array, and nums1 already contains extra space for nums2. 💡 Approach: To avoid overwriting elements in nums1, we use a three-pointer approach: Start from the end of both arrays. Compare the elements and place the larger one at the back (nums1[pMerge]). Move pointers accordingly until all elements are merged. 💻 Java Code: class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m - 1, p2 = n - 1, pMerge = m + n - 1; while (p2 >= 0) { if (p1 >= 0 && nums1[p1] > nums2[p2]) { nums1[pMerge--] = nums1[p1--]; } else { nums1[pMerge--] = nums2[p2--]; } } } } ⏱️ Complexity: Time: O(m + n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) A simple yet elegant example of solving array problems in-place using smart pointer manipulation!
To view or add a comment, sign in
-
🌳 Trees in Java — From Layman to Pro (2025 Edition) Ever wondered how hierarchical structures like file systems, JSON, or company org charts are represented in code? That’s where Trees come in — nature’s most elegant data structure 🌱 In my latest article, I break down Trees from scratch — starting with simple Java examples to architect-level insights: What makes a Tree different from linear structures Building and traversing a Binary Search Tree (BST) Understanding metrics like height, depth, diameter, balance factor, and leaf count How Trees relate to real-world systems (Kubernetes, APIs, ML models, databases) And yes, a complete working Java program you can run today 🚀 If you’ve ever felt Trees were confusing — this one will make them crystal clear. Simple visuals, intuitive explanations, and modern Java code (2025-ready). 👉 Read here: https://lnkd.in/dhsQQj2p #Java #DataStructures #SystemDesign #Coding #Learning #SoftwareEngineering #Algorithms #TechEducation
To view or add a comment, sign in
-
What is the difference between map() and flatMap() in Java 8 Streams? Answer: map() Transforms each element of the stream into another object. It performs a one-to-one mapping. List<String> names = Arrays.asList("john", "steve"); List<Integer> lengths = names.stream() .map(String::length) .collect(Collectors.toList()); Result: [4, 5] flatMap() Used to flatten nested structures. It performs a one-to-many mapping. List<List<Integer>> numbers = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4) ); List<Integer> flattened = numbers.stream() .flatMap(List::stream) .collect(Collectors.toList()); Result: [1, 2, 3, 4] Key difference: map() transforms data flatMap() flattens nested data structures
To view or add a comment, sign in
-
Option 1: Concise & Achievement-Focused Solved a classic Linked List problem: "Remove Nth Node From End of List" (LeetCode #19)! Successfully implemented the Java solution. This exercise was a great review of using a dummy node and the two-pointer approach to handle linked list operations efficiently. Option 2: Detailed & Technical Insight Deep dive into Linked Lists today! Just wrapped up the LeetCode problem "19. Remove Nth Node From End of List." Key takeaway from the solution: The most robust approach involves: Using a dummy node to simplify edge cases (like removing the head). Employing the two-pointer technique (slow/fast or previous/current) to find the target node in a single pass. The challenge is positioning the 'previous' pointer correctly so that when the fast pointer hits the end, the previous pointer is exactly one node before the node to be removed. Great practice for improving pointer manipulation skills! Option 3: Simple & Direct Happy to share a successful solution for LeetCode 19: Remove Nth Node From End of List! https://lnkd.in/d5TRq5b9
To view or add a comment, sign in
-
-
🚀 StringBuffer vs. StringBuilder: Choosing the Right Tool for Performance! ⚡ When dealing with mutable sequences of characters in Java, we choose between StringBuffer and StringBuilder. Both are designed to handle repeated modifications efficiently, but they serve different needs due to their underlying mechanics. The primary difference lies in thread safety. 1. The Role of StringBuffer The StringBuffer class is thread-safe because its methods are synchronized. This means that only one thread can access a StringBuffer instance at any given time. This synchronization ensures data integrity and prevents conflicts when multiple parts of a program might try to modify the string concurrently. The trade-off for this safety is performance. Because of the overhead required to manage locks for synchronization, StringBuffer is slower than StringBuilder. It was introduced early, in Java 1.0, and remains the choice for robust, multi-threaded environments where data consistency is paramount. 2. The Role of StringBuilder The StringBuilder class, introduced later in Java 5.0 as a faster alternative, is not thread-safe (it is unsynchronized). Because it lacks the synchronization overhead, StringBuilder is significantly faster than StringBuffer. For this reason, it is the ideal choice for text manipulation in single-threaded environments where performance is the priority and there is no risk of concurrent access causing data corruption. The Takeaway The choice is simple and driven by the environment: For most common applications running on a single thread, use the faster StringBuilder. Reserve StringBuffer only for situations where data is shared and modified across multiple threads. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #StringBuffer #StringBuilder ##PerformanceOptimization #TechEducation #Codegnan
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