💡 Day 97 of My DSA Challenge – Single Element in a Sorted Array 🔷 Problem : 540. Single Element in a Sorted Array 🔷 Goal : Find the single element that appears only once in a sorted array where all other elements appear exactly twice, in O(log n) time and O(1) space. 🔷 Key Insight : The array is sorted, and elements appear in pairs — except for one. We can use Binary Search on Indices : Check the mid element and compare it with neighbors. If mid is unique → return it. Otherwise, depending on whether the pair is on the left or right and the parity of the remaining elements, move left or right. This works because the single element shifts the pairing pattern in the array, allowing us to discard half the search space each time. 🔷 My Java Approach : 1️⃣ Binary search over array indices. 2️⃣ Compare mid with neighbors to detect the single element. 3️⃣ Adjust search space using parity logic. 🔷 Complexity : Time → O(log n) Space → O(1) Binary search isn’t just for sorted numbers — it can also be applied to patterns and structural properties in arrays. Recognizing such patterns allows efficient solutions even when the array has special constraints. 🚀 #100DaysOfCode #Day97 #LeetCode #DSA #Java #ProblemSolving #BinarySearch #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
How to find a single element in a sorted array using binary search
More Relevant Posts
-
🌟 Day 44 – LeetCode Practice Problem: Product of Array Except Self (LeetCode #238) 📌 Concept: Given an integer array, create a new array where each element equals the product of all other elements except itself, without using division. 🧠 My Approach: First pass → compute prefix products (multiply everything before current index) Second pass → compute suffix products (multiply everything after current index) Combine both to get the result for each index efficiently No extra multiplication array used — optimized and clean logic ⚡ This avoids division and runs in linear time — exactly what the problem demands ✅ 📈 Result: ✅ Accepted ⚡ Runtime: 2 ms (Beats ~87%) 📦 Memory: Efficient usage 💡 Key Learning: This problem reinforces the power of prefix & suffix computation — a common trick in array manipulation + interview favorite. Great way to improve problem-solving without relying on brute force or division. --- 🚀 Growing stronger every day in DSA! #LeetCode #DSA #Java #ProblemSolving #PrefixSuffix #CodingJourney #ArrayProblems #LearningMindset
To view or add a comment, sign in
-
-
DSA Practice – Day 48 🚀 Problem: Sort Array by Parity(LeetCode 905) Problem Statement: Given an integer array nums, move all even integers to the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. ⚡ Brute Force Approach: Create a new array. First, add all even numbers from nums to it. Then, add all odd numbers. Return the new array. Time Complexity: O(n) Space Complexity: O(n) (because of the extra array) ⚡ Optimal Approach (Two Pointer Technique): Use two pointers — one at the start (left) and one at the end (right). If the left element is odd and the right is even, swap them. Move pointers accordingly until they meet. This sorts even and odd numbers in-place without extra space. Time Complexity: O(n) Space Complexity: O(1) ✨ What I Learned: How to use the two-pointer approach for in-place array rearrangement. Simple logic can drastically reduce space usage in problems like these. #DSA #LeetCode #Java #Arrays #TwoPointer #ProblemSolving #Coding #InterviewPrep
To view or add a comment, sign in
-
-
💡 Day 99 of My DSA Challenge – Split Array Largest Sum 🔷 Problem: 410. Split Array Largest Sum 🔷 Goal: Split the array into k non-empty subarrays such that the largest subarray sum is as small as possible. 🔷 Key Insight: This is a classic Binary Search on the Answer problem — the goal isn’t to find a position, but the minimum possible value of the largest subarray sum. Here’s how: The lower bound of our search space is the maximum element in the array (a subarray must at least handle this value). The upper bound is the total sum of the array (one subarray takes all elements). For each mid (possible largest sum), we simulate how many subarrays are needed. If we need more than k, it means our mid is too small → move right. Else, we can try smaller sums → move left. 🔷 My Java Approach: 1️⃣ Define helper isPossible() to simulate how many subarrays form under a max limit. 2️⃣ Apply Binary Search on range [max(nums), sum(nums)]. 3️⃣ Narrow down to the smallest feasible largest sum. 🔷 Complexity: Time → O(n × log(sum(nums))) Space → O(1) This problem is a perfect blend of binary search intuition + greedy validation. It pushes you to think beyond array indices — to apply binary search to ranges of answers instead. Every problem like this sharpens both algorithmic depth and logical structure. 🚀 #100DaysOfCode #Day99 #LeetCode #DSA #Java #ProblemSolving #BinarySearch #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
Day 53 of My DSA Challenge Problem: Find the pair in an array whose sum is closest to and less than or equal to a given target. Approach: Instead of checking every possible pair (O(N²)), I optimized the solution using the Two-Pointer Technique. Sort the array. Initialize two pointers — one at the start and one at the end. Move the pointers based on the sum compared to the target: If the sum is less than or equal to the target, record it and move the left pointer forward. If the sum exceeds the target, move the right pointer backward. This ensures that every pair is checked efficiently, and the closest valid sum is captured. Complexity: Time: O(N log N) (due to sorting) Space: O(1) #Day53 #DSAChallenge #TwoPointers #Sorting #Optimization #ProblemSolving #DSA #Java #CodingChallenge #Algorithms #DataStructures #100DaysOfCode #GeeksforGeeks #LeetCode #ProgrammingJourney #CodingCommunity
To view or add a comment, sign in
-
-
💡 Day 98 of My DSA Challenge – Longest Subsequence With Limited Sum 🔷 Problem: 2389. Longest Subsequence With Limited Sum 🔷 Goal: For each query, find the maximum number of elements from nums that can form a subsequence with a sum ≤ query value. 🔷 Key Insight: To maximize the subsequence size, we should always pick smaller elements first — this is a greedy choice. Hence, sorting the array ensures we can accumulate the smallest elements until the sum exceeds the query limit. Approach outline: 1️⃣ Sort the array nums. 2️⃣ For each query, add elements one by one until the sum crosses the limit. 3️⃣ Return the count of elements that fit within the limit. This logic can also be optimized further using prefix sums + binary search, but the greedy approach works perfectly within given constraints. 🔷 My Java Approach: Sort the array. Use a helper function to count how many elements fit under the query sum. Store each result in the answer array. 🔷 Complexity: Time → O(n log n + n × m) Space → O(1) Sometimes, simplicity wins. This problem reinforces the power of greedy thinking — starting small, building up gradually, and knowing when to stop. Recognizing such patterns is key to writing clean and intuitive code. 🚀 #100DaysOfCode #Day98 #LeetCode #DSA #Java #ProblemSolving #GreedyAlgorithm #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
🌟 #PostLog23🌟 Problem: 1539. Kth Missing Positive Number This one was about finding the k-th missing positive integer from a sorted array — and I managed to solve it efficiently using binary search, achieving a 0 ms runtime (100% faster submissions) 🚀 💡 Key idea: Instead of checking each missing number one by one, binary search helps to quickly find the point where the count of missing numbers reaches k. This brings the time complexity down to O(log n) — much faster than a linear scan. ✅ Concepts reinforced: Binary search optimization Handling edge cases in sorted arrays Mathematical reasoning in array indexing #LeetCode #CodingChallenge #Java #BinarySearch #ProblemSolving #LearningJourney #DSA
To view or add a comment, sign in
-
-
🚀 Day 399 of #500DaysOfCode 🔹 Problem: 129. Sum Root to Leaf Numbers 🔹 Difficulty: Medium 🔹 Language Used: Java ☕ 🧩 Problem Summary: Given the root of a binary tree containing digits (0–9), each root-to-leaf path represents a number. Our task is to find the sum of all numbers formed by these root-to-leaf paths. 💡 Key Idea: We can use Depth-First Search (DFS) to traverse the tree. As we go deeper, we build the current number by multiplying by 10 and adding the current node’s value. When we reach a leaf node, we add that full number to our total sum. ⚙️ Approach: 1️⃣ Start DFS from the root with currentSum = 0. 2️⃣ At each step, update currentSum = currentSum * 10 + node.val. 3️⃣ When reaching a leaf node, return that number. 4️⃣ Combine left and right subtree results to get the total sum. ✅ Example: Input: root = [1,2,3] Output: 25 Paths: 12 + 13 = 25 📘 Lesson Learned: Sometimes, problems that seem about “trees” are really about number construction — a great reminder that recursion can elegantly combine logic with mathematics 🌱 #Day399 #Java #LeetCode #BinaryTree #DFS #ProblemSolving #CodingChallenge #LearnEveryday #Programming #Developer #500DaysOfCode
To view or add a comment, sign in
-
-
💡 Day 104 of My DSA Challenge – Combinations 🔷 Problem : 77. Combinations 🔷 Goal : Generate all possible combinations of k numbers chosen from the range [1, n]. Example → Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 🔷 Key Insight : This is a backtracking problem — where we explore all possible ways of picking elements while maintaining order and avoiding repetition. The core difference from permutations is that the order of elements doesn’t matter — [1,2] and [2,1] are the same combination. 🔷 Approach : 1️⃣ Start from the first number (idx = 1). 2️⃣ At each step, decide whether to include the current number in the combination or skip it. 3️⃣ Recursively build combinations until the list size reaches k. 4️⃣ Backtrack to explore other possibilities. 🔷 My Java Approach : Used recursion to explore all inclusion/exclusion choices. Added combinations when list size equals k. Backtracked after each recursive call to maintain correct state. 🔷 Complexity : Time → O(C(n, k)) Space → O(k) (for recursion and temporary list) This problem strengthens understanding of decision trees and combinatorial logic, which form the backbone of many recursive and dynamic programming patterns. Every problem adds a new layer to logical thinking — today, it was about choosing without caring about order, but caring deeply about structure. #Day104 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Backtracking #Recursion #Combinations #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #EngineerMindset #DeveloperJourney #GrowthMindset #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
#Day_31 Today’s challenge was an interesting matrix binary search problem — “Find a Peak Element II”-> it's a medium level question. The task: Given a 2D grid, find any element that’s strictly greater than its top, bottom, left, and right neighbors. A brute-force solution would check every element’s neighbors — but that’s O(m × n). Instead, I used a binary search on columns to cut the search space efficiently. Here’s the idea: Pick the middle column. Find the maximum element in that column. Compare it with its left and right neighbors. If it’s greater than both — you’ve found a peak. Otherwise, move to the side that has a larger neighbor (since a peak must exist there). This clever approach brings the complexity down to O(m × log n) — a huge win on large matrices. This problem was a great reminder that binary search isn’t just for 1D arrays — it can be applied creatively in multiple dimensions too #Coding #LeetCode #Java #BinarySearch #ProblemSolving #LearningEveryday
To view or add a comment, sign in
-
-
🔥 Day 111 of My DSA Challenge – Subsets II (Handling Duplicates) 🔷 Problem : 90. Subsets II 🔷 Goal : Generate all possible subsets of an array that may contain duplicates No duplicate subsets allowed 🔷 Key Insight : This is an extension of the classic Subsets / Power Set problem — but here the array can contain duplicates, so we must avoid repeating subsets. Core idea : At each element, you can : ✅ Include it ❌ Skip it But when skipping, you must skip all duplicates of that element at that step this ensures all generated subsets are unique. 🔷 Approach : 1️⃣ Sort the array to group duplicates 2️⃣ Use recursion + backtracking to try all possibilities 3️⃣ Skip duplicate values when they appear in the same decision branch Time Complexity: O(2ⁿ) Space Complexity: O(n) Subsets II builds the backtracking mindset further: When values repeat, skip duplicate branches — not decisions. This pattern is powerful for problems like : ✅ Combination Sum II ✅ Unique permutations ✅ Partitioning problems Little wins → Big breakthroughs Every problem improves logic and patience. On to the next one 👊🔥 #Day111 #100DaysOfCode #LeetCode #DSA #Java #Backtracking #Recursion #Subsets #PowerSet #CodingChallenge #Algorithms #ProblemSolving #DeveloperJourney
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