🚀 Day 18/30– DSA Challenge 📌 LeetCode Problem – Search Insert Position 📝 Problem Statement Given a sorted array nums and a target value, return the index if found. If not found, return the index where it would be inserted in order. 📌 Example Input: nums = [1,3,5,6] target = 2 Output: 1 Explanation: 2 should be inserted at index 1. 💡 Key Insight This is a binary search variation. 👉 If element exists → return index 👉 If not → return the position where it should be And that position is exactly where left ends after the loop. 🚀 Algorithm 1️⃣ Initialize: left = 0 right = n - 1 2️⃣ While left <= right: Find mid If equal → return mid If smaller → move left Else → move right 3️⃣ If not found → return left ✅ Java Code (Optimal O(log n)) class Solution { public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return left; } } ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 📊 Performance ⚡ Runtime: 0 ms (Beats 100%) 💾 Memory: ~44 MB 📚 Key Learnings – Day 18 ✔ Binary Search is more than just finding elements ✔ “Insert position” problems are common variations ✔ Final value of left is very important ✔ Always avoid overflow → use mid = left + (right - left)/2 Simple problem. Strong concept. Perfect execution. Day 18 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #BinarySearch #LeetCode
Binary Search Insert Position in Sorted Array
More Relevant Posts
-
🚀 Day 17/30– DSA Challenge 📌 LeetCode Problem – Plus One 📝 Problem Statement You are given a large integer represented as an array of digits. Increment the integer by one and return the resulting array. 📌 Example Input: digits = [1,2,3] Output: [1,2,4] 📌 Edge Case Input: [9,9,9] Output: [1,0,0,0] 💡 Key Insight Addition starts from the last digit. 👉 If digit < 9 → just add 1 and return 👉 If digit == 9 → it becomes 0 and carry moves left If all digits are 9 → create a new array. 🚀 Algorithm 1️⃣ Traverse from right → left 2️⃣ If digit < 9: Increment it Return array 3️⃣ Else: Set digit = 0 Continue 4️⃣ If loop ends → all were 9 Create new array of size n+1 Set first element = 1 ✅ Java Code (Optimal O(n)) class Solution { public int[] plusOne(int[] digits) { for (int i = digits.length - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } // All digits were 9 int[] result = new int[digits.length + 1]; result[0] = 1; return result; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) (except edge case) 📚 Key Learnings – Day 17 ✔ Handle carry carefully ✔ Think from right to left ✔ Edge cases matter more than logic here ✔ Small problems test attention to detail Simple idea. Tricky edge case. Clean implementation. Day 17 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 21/30 – DSA Challenge 📌 LeetCode Problem – Median of Two Sorted Arrays 📝 Problem Statement Given two sorted arrays nums1 and nums2, find the median of the combined array. 📌 Example Input: nums1 = [1,2] nums2 = [3,4] Output: 2.5 💡 My Approach Instead of using complex binary search, I followed a simple and reliable method: 👉 Merge both arrays 👉 Sort the merged array 👉 Find the median This approach is easy to understand and implement. 🚀 Algorithm 1️⃣ Create a new array of size n1 + n2 2️⃣ Copy elements of both arrays 3️⃣ Sort the merged array 4️⃣ If length is odd → return middle element 5️⃣ If even → return average of two middle elements ✅ Java Code import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] merged = new int[n1 + n2]; for (int i = 0; i < n1; i++) { merged[i] = nums1[i]; } for (int i = 0; i < n2; i++) { merged[n1 + i] = nums2[i]; } Arrays.sort(merged); int n = merged.length; if (n % 2 == 1) { return merged[n / 2]; } else { return (merged[n / 2 - 1] + merged[n / 2]) / 2.0; } } } ⏱ Complexity Time Complexity: O((n + m) log(n + m)) Space Complexity: O(n + m) 📚 Key Learnings – Day 21 ✔ Simple solutions are often easiest to implement ✔ Always understand problem constraints ✔ This problem can be optimized further using binary search ✔ Multiple approaches exist — choose based on context Simple approach. Clear logic. Strong understanding. Day 21 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 13 of My DSA Journey Today I worked on an interesting problem: K-Sorted Array Check 🧩 Problem Statement Given an array of distinct elements, determine whether it is a k-sorted array. 👉 A k-sorted array means: Each element is at most k distance away from its correct position in the sorted array. 🧠 Approach Used ✔️ Created a sorted copy of the array ✔️ Stored element → correct index using HashMap ✔️ Checked if the distance between current index and correct index is ≤ k 💻 Code (Java) class Solution { static String isKSortedArray(int arr[], int n, int k) { HashMap<Integer,Integer> map = new HashMap<>(); int[] sorted = arr.clone(); Arrays.sort(sorted); for(int i = 0; i < n; i++){ map.put(sorted[i], i); } for(int i = 0; i < n; i++){ int key = arr[i]; if(Math.abs(map.get(key) - i) > k){ return "No"; } } return "Yes"; } } ⚡ Optimized Insight We can also solve this using a Min Heap (Priority Queue) in O(n log k) time, which is useful when the array is nearly sorted. 🎯 Key Learning 👉 Don’t modify the original array when position matters 👉 Always think about index mapping in such problems 👉 Optimization with Heap is a must-know pattern Consistency > Motivation. See you on Day 14 💪 #DSA #Java #CodingJourney #100DaysOfCode #GeeksforGeeks #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
. 🚀 Day 27/30 – DSA Challenge 📌 LeetCode Problem – Middle of the Linked List 📝 Problem Statement Given the head of a singly linked list, return the middle node of the linked list. 👉 If there are two middle nodes, return the second middle node. 📌 Example Input: 1 → 2 → 3 → 4 → 5 Output: 3 📌 Even Case Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 4 💡 My Approach (Counting Method) Instead of using two pointers, I used a two-step approach: 👉 First count total nodes 👉 Then move to the middle 🚀 Algorithm 1️⃣ Traverse the list and count nodes 2️⃣ Calculate middle index: mid = count / 2 3️⃣ Traverse again till mid position 4️⃣ Return that node ✅ Java Code class Solution { public ListNode middleNode(ListNode head) { int count = 0; ListNode temp = head; // Step 1: Count nodes while (temp != null) { count++; temp = temp.next; } // Step 2: Find middle index int mid = count / 2; // Step 3: Traverse to middle temp = head; for (int i = 0; i < mid; i++) { temp = temp.next; } return temp; } } ⏱ Complexity Time Complexity: O(n) (two traversals) Space Complexity: O(1) 📚 Key Learnings – Day 27 ✔ Problems can have multiple valid approaches ✔ Counting method is simple and intuitive ✔ Always think about optimizing further ✔ Same problem can be solved in one pass using fast & slow pointers Simple idea. Clear logic. Solid understanding. Day 27 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
To view or add a comment, sign in
-
-
🚀 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
-
-
🔥 𝗗𝗮𝘆 𝟵𝟰/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟭𝟱𝟯𝟵. 𝗞𝘁𝗵 𝗠𝗶𝘀𝘀𝗶𝗻𝗴 𝗣𝗼𝘀𝗶𝘁𝗶𝘃𝗲 𝗡𝘂𝗺𝗯𝗲𝗿 | 🟢 Easy | Java Marked as Easy — but the optimal solution is pure binary search brilliance. 🎯 🔍 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Given a sorted array, find the kth missing positive integer. Linear scan works — but can we do O(log n)? 💡 𝗧𝗵𝗲 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 At index i, the value arr[i] should be i+1 in a complete sequence. So missing numbers before arr[i] = arr[i] - 1 - i This lets us binary search on the count of missing numbers! ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗕𝗶𝗻𝗮𝗿𝘆 𝗦𝗲𝗮𝗿𝗰𝗵 ✅ If arr[mid] - 1 - mid < k → not enough missing numbers yet, go right ✅ Else → too many missing, go left ✅ After the loop, left + k gives the exact answer 𝗪𝗵𝘆 𝗹𝗲𝗳𝘁 + 𝗸? After binary search, left is the index where the kth missing number falls beyond. left numbers exist in the array before that point, so the answer is left + k. No extra passes needed. ✨ 📊 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 ⏱ Time: O(log n) — vs O(n) linear scan 📦 Space: O(1) This is a perfect example of binary searching on a derived condition, not just a value. A real upgrade from the naive approach. 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gVYcjNS6 𝟲 𝗺𝗼𝗿𝗲 𝗱𝗮𝘆𝘀. 𝗧𝗵𝗲 𝗳𝗶𝗻𝗶𝘀𝗵 𝗹𝗶𝗻𝗲 𝗶𝘀 𝗿𝗶𝗴𝗵𝘁 𝘁𝗵𝗲𝗿𝗲! 🏁 #LeetCode #Day94of100 #100DaysOfCode #Java #DSA #BinarySearch #Arrays #CodingChallenge #Programming
To view or add a comment, sign in
-
🧠 LeetCode POTD — The Biggest Hint Was Hidden in One Line 1855. Maximum Distance Between a Pair of Values Today's problem looked tricky at first considering the time complexity. We need to find indices (i, j) such that: 👉 i <= j 👉 nums1[i] <= nums2[j] And maximize: 👉 j - i ━━━━━━━━━━━━━━━━━━━ My first instinct? Try brute force combinations. Check many pairs. Maybe binary search. But I was missing the most important line in the question: Both arrays are non-increasing (sorted). That one detail changes everything. ━━━━━━━━━━━━━━━━━━━ 💡 Once I noticed that, the solution became a clean two-pointer approach. Start with: 👉 i = 0 in nums1 👉 j = 0 in nums2 Then: If nums1[i] <= nums2[j] 👉 This pair is valid 👉 Update answer with j - i 👉 Move j forward to try for a bigger distance Else: 👉 Current i is too large 👉 Move i forward Because arrays are sorted, once a pair fails, moving i is the only useful move. ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: The challenge wasn't the coding. It was reading carefully enough to spot the property that unlocks the solution. ✅ Sometimes the answer is already in the problem statement. ✅ You just have to notice it. Curious — did anyone else miss the sorted hint at first? 👀 #LeetCode #TwoPointers #ProblemSolving #SoftwareEngineering #DSA #Java #c++ #SDE
To view or add a comment, sign in
-
-
✅ Solved: Majority Element — LeetCode | Boyer-Moore Voting Algorithm Just got accepted on all 53/53 test cases with 2ms runtime (beats 70.59% of Java submissions)! 🎯 Here's what I learned: 🧠 The Problem: Given an array, find the element that appears MORE than ⌊n/2⌋ times. It's guaranteed to always exist. 💡 The Approach — Boyer-Moore Voting Algorithm: Instead of using a HashMap (O(n) space), I used a clever O(1) space trick: Treat elements like "votes" — keep a candidate and a counter When count hits 0 → pick the current element as the new candidate When you see the same element → count++ When you see a different element → count-- The majority element always "survives" the cancellation 🔑 Key Insight: The majority element appears more than all other elements COMBINED. So even if every other element "cancels" one occurrence of the majority, it still has votes left at the end. 🗓️ Submitted: April 13, 2026 If you're preparing for DSA interviews, this is a must-know pattern. It shows up in stream processing, voting systems, and distributed consensus problems too. Drop a comment if you've solved this a different way — I'd love to compare approaches! 🚀 #LeetCode #DSA #Java #BoyerMoore #CodingInterview #ProblemSolving #100DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
Explore related topics
- LeetCode Array Problem Solving Techniques
- Leetcode Problem Solving Strategies
- Common Algorithms for Coding Interviews
- Problem Solving Techniques for Developers
- Approaches to Array Problem Solving for Coding Interviews
- Strategies for Solving Algorithmic Problems
- Solving Sorted Array Coding Challenges
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