Problem :- Search Insert Position (LeetCode 35) Problem Statement :- Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Approach :- Binary Search i - Uses Binary Search to efficiently find the target or its position in a sorted array. ii - Compares nums[mid] with target and adjusts search range (start or end). iii - Loop ends when target is not found, and correct position is crossed. iv - If target > nums[mid] => mid + 1 Else => mid v - Time Complexity : O(log n) vi - Space Complexity : O(1) class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid = 0; while (start <= end) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return (target > nums[mid]) ? mid + 1 : mid; } } Key Takeaway :- Binary Search efficiently finds the position (or insertion point) by repeatedly dividing the search space. How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #BinarySearch
Optimize Binary Search for Target Position in Sorted Array
More Relevant Posts
-
Problem :- Remove Duplicates from Sorted Array (LeetCode 26) Problem Statement :- Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements. The relative order of elements should be kept the same. Approach :- Two Pointer Technique i - Use pointer k to track position of unique elements ii - Traverse array from index 1 iii - If nums[i] != nums[k-1], place it at nums[k] iv - Time Complexity : O(n) v - Space Complexity : O(1) class Solution { public int removeDuplicates(int[] nums) { int k = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[k - 1]) { nums[k] = nums[i]; k++; } } return k; } } Key Takeaway :- Since the array is already sorted, duplicates are adjacent. Using two pointers allows us to efficiently overwrite duplicates in a single pass without extra space. If yes, how would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
To view or add a comment, sign in
-
-
Problem :- Merge Sorted Array (LeetCode 88) Problem Statement :- You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n representing the number of elements in nums1 and nums2 respectively. Merge nums2 into nums1 as one sorted array. The final sorted array should not be returned, but instead be stored inside nums1. Approach :- Three Pointer Technique i - Use three pointers: i → last element of nums1 (m-1) j → last element of nums2 (n-1) k → last position of nums1 (m+n-1) ii - Compare nums1[i] and nums2[j], place larger at nums1[k] iii - Move pointers accordingly iv - If elements left in nums2, copy them v - Time Complexity : O(m + n) vi - Space Complexity : O(1) class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m -1; int p2 = n -1; int p = m + n -1; while(p1 >=0 && p2 >= 0){ if(nums1[p1] > nums2[p2]){ nums1[p] = nums1[p1]; p1--; }else { nums1[p] = nums2[p2]; p2--; } p--; } while (p2 >= 0){ nums1[p] = nums2[p2]; p2--; p--; } } } Key Takeaway :- Instead of merging from the front (which causes shifting), start from the end and place elements in correct position using three pointers. How would you optimize this further? Is there any way to handle merging without using extra space in other variations? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers
To view or add a comment, sign in
-
-
🚀 Day 23/30 – DSA Challenge 📌 LeetCode Problem – Remove Duplicates from Sorted List 📝 Problem Statement Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the modified linked list. 📌 Example Input: 1 → 1 → 2 → 3 → 3 Output: 1 → 2 → 3 💡 Key Insight Since the list is sorted, 👉 duplicates will always be adjacent. So we don’t need extra space or hashing. 🔥 Optimal Approach – Single Traversal 🧠 Idea Traverse the list and compare: Current node Next node If they are equal → skip the next node Else → move forward 🚀 Algorithm 1️⃣ Start from head 2️⃣ While current != null && current.next != null 3️⃣ If: current.val == current.next.val 👉 Skip duplicate: current.next = current.next.next 4️⃣ Else: Move to next node ✅ Java Code (Optimal O(n)) class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.val == current.next.val) { current.next = current.next.next; } else { current = current.next; } } return head; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) 📚 Key Learnings – Day 23 ✔ Sorted data simplifies problems ✔ Linked list manipulation requires careful pointer handling ✔ No extra space needed when duplicates are adjacent ✔ Always check current.next != null to avoid errors Simple structure. Clean pointer logic. Efficient solution. Day 23 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
To view or add a comment, sign in
-
-
🚀 LeetCode — Problem 18 | Day 16 💡 Problem: 4Sum 🧠 Problem: Given an array nums and a target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that their sum equals the target. 🧠 Approach (Sorting + Two Pointers): Sort the array: Essential for two-pointer movement and skipping duplicates. Nested Loops: Fix the first two elements using two loops (i and j). Two Pointers: Use left and right pointers for remaining two elements. Skip Duplicates: Avoid duplicate quadruplets by skipping same values for i, j, left, right. ⚙️ Core Logic: Fix i and j, then set left = j + 1 and right = n - 1. Compute sum = nums[i] + nums[j] + nums[left] + nums[right]. If sum == target: Add quadruplet to result and move both pointers while skipping duplicates. If sum < target: Move left++ If sum > target: Move right-- ⏱ Time Complexity: O(n^3) 📦 Space Complexity: O(1) (excluding output list) ⚠️ Edge Cases: - Array size < 4 - Integer overflow (use long for sum) - Duplicate values leading to repeated results 🔍 Insight: 4Sum is an extension of 3Sum. Fixing two numbers reduces problem to two-pointer search. 🔑 Key Learning: - Extending two-pointer technique to higher dimensions - Handling duplicates efficiently in sorted arrays - Using long to avoid overflow "Use sorting and nested two pointers to reduce complexity from O(n^4) to O(n^3) while ensuring unique quadruplets." #LeetCode #DSA #Java #TwoPointers #CodingJourney #4Sum #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 86 — Prefix Sum Pattern (Introduction) Today I started learning the Prefix Sum pattern — a fundamental technique for array problems where decisions at a given index depend on the sum of previous elements. Unlike sliding window, prefix sum handles negative numbers gracefully. 📌 What is Prefix Sum? At index i, the prefix sum is the sum of all elements from the start up to i-1. It stores “historical information” to make efficient decisions. 🧠 Why Prefix Sum > Sliding Window for Negatives? Sliding window fails with negatives because removing a negative actually increases the sum — breaking the logic of expanding/shrinking. Prefix sum remains effective. 📊 Four Categories of Prefix Sum Problems: 1️⃣ Left‑Right Comparisons (e.g., Pivot Index) → Can often be solved with simple variables (no extra arrays). 2️⃣ Exact Sums (Subarray Sum = K) → Requires a HashMap to store and lookup previous prefix sums. 3️⃣ Shortest Window with Sum ≥ K (with negatives) → Needs a Deque (double‑ended queue). 4️⃣ Range Sum Queries → Advanced techniques like Merge Sort on prefix array. 🔧 General Template: Initialize data structure (variable, array, or HashMap). Loop through the array, updating prefix information. Check problem‑specific condition. ⚡ Optimization Insight (Pivot Index Example): Instead of storing both prefix and suffix arrays, use: Total Sum = Left Sum + arr[i] + Right Sum → Right Sum = Total Sum - Left Sum - arr[i] This finds the pivot using only O(1) space. 💡 Takeaway: Prefix sum is a pattern, not just an algorithm. Recognizing when to use it — especially with negative numbers — unlocks efficient solutions for subarray sum problems. No guilt about past breaks — just adding another powerful pattern to the toolkit. #DSA #PrefixSum #ArrayPatterns #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
To view or add a comment, sign in
-
-
🧠 LeetCode POTD — From TLE to Optimized Thinking 3488. Closest Equal Element Queries At first, the approach felt straightforward. For each query: 👉 Start from the given index 👉 Expand left and right (circularly) 👉 Find the closest same element ━━━━━━━━━━━━━━━━━━━ 💥 The problem? This works… but doesn't scale. If there are q queries and n elements: → Each query can take O(n) → Total = O(n × q) 👉 This leads to TLE for large inputs. ━━━━━━━━━━━━━━━━━━━ 💡 So what's the issue? We are repeating the same work again and again for every query. ━━━━━━━━━━━━━━━━━━━ 📌 Better Approach: Preprocess the array. 👉 Use a map: value → list of indices Example: nums = [1, 2, 1, 3, 1] → 1 → [0, 2, 4] Now for each query: Get all indices of that value If only one occurrence → answer = -1 Else: 👉 Use binary search to find the closest index 👉 Check neighbors (left & right) 📌 Since the array is circular: Distance = min(|i - j|, n - |i - j|) ━━━━━━━━━━━━━━━━━━━ 💡 Complexity now: → Preprocessing: O(n) → Each query: O(log n) 👉 Total: O(n + q log n) ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: The solution isn't complicated. The key is realizing: 👉 "This is not a single query problem." Once you see that, the shift from brute force → optimized becomes obvious. ✅ Sometimes optimization is not about faster code ✅ It's about not repeating the same work Curious if someone solved it differently 👀 #LeetCode #DataStructures #ProblemSolving #SoftwareEngineering #DSA #C++ #Java #SDE
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
-
-
**Day 109 of #365DaysOfLeetCode Challenge** Today’s problem: **132 Pattern (LeetCode 456)** This problem looks tricky at first because it asks for a hidden subsequence: Find indices `i < j < k` such that: `nums[i] < nums[k] < nums[j]` That forms the **132 pattern** 💡 **Core Idea: Use a Monotonic Stack** Instead of checking all triplets (**O(n³)** ❌), we scan from **right to left**. Why reverse? Because while moving backward: * We try to build possible `3` values using a stack * Track the best possible `2` using a variable called `third` 👉 If we ever find a number smaller than `third`, then: `nums[i] < third < nums[j]` 📌 **Approach:** * Traverse from end to start * Maintain decreasing stack * Pop smaller elements and update `third` * If current number < `third` → return true ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Some array problems become much easier when traversed **backward instead of forward**. 💭 **Key Takeaway:** When the problem asks for hidden order relations: 👉 Think stacks 👉 Think reverse traversal 👉 Think maintaining candidates dynamically This was a great reminder that brute force is rarely the final answer #LeetCode #DSA #MonotonicStack #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
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