🚀 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
Minimum Distance to Target Element in Array
More Relevant Posts
-
🚀 Day 31/40 – DSA Challenge 📌 LeetCode Problem – Mirror Distance of an Integer 📝 Problem Statement Given an integer n, compute its mirror distance: | n - reverse(n) | Where reverse(n) is formed by reversing the digits of n. 📌 Example Input: n = 25 Output: 27 Explanation: reverse(25) = 52 |25 - 52| = 27 💡 Key Insight The main task is correctly reversing the number. 👉 Extract digits one by one 👉 Build the reversed number ⚠️ Important: Do not lose the original value of n while reversing. 🚀 Algorithm 1️⃣ Store original value 2️⃣ Reverse the number using modulo and division 3️⃣ Return absolute difference ✅ Java Code (Correct & Safe) class Solution { public int mirrorDistance(int n) { int original = n; int reversed = 0; while (n != 0) { int digit = n % 10; reversed = reversed * 10 + digit; n /= 10; } return Math.abs(original - reversed); } } ⏱ Complexity Time Complexity: O(d) (d = number of digits) Space Complexity: O(1) ⚠️ Common Mistake (You Had This Earlier) return Math.abs(n - reversed); ❌ 👉 Because n becomes 0 after the loop ✔ Fix: return Math.abs(original - reversed); ✅ 📚 Key Learnings – Day 31 ✔ Preserve original values during transformations ✔ Digit extraction using % and / is fundamental ✔ Small mistakes can break correct logic ✔ Always dry run with simple inputs Simple problem. Careful implementation. Bug fixed, concept clear. Day 31 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Math #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 21/40 – 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 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
Problem Solved: Super Reduced String (Stack Approach) Today I solved an interesting string problem where we repeatedly remove adjacent matching characters until no more reductions are possible. 💡 Key Idea: Used a StringBuilder as a stack to efficiently remove adjacent duplicates in a single pass. 🔧 Tech Used: Java | String Manipulation | Stack Concept 📌 What I Learned: How stack-based thinking simplifies string problems Writing optimized O(n) solutions Clean handling of edge cases like empty string 📊 Example: Input: aaabccddd Output: abd This problem is a great example of how simple logic + the right data structure can lead to efficient solutions. #Java #DataStructures #CodingPractice #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
#CodeEveryday — My DSA Journey | Day 2 🧩 Problem Solved: Combination Sum II (LeetCode) 💭 What I Learned: Used backtracking to generate all unique combinations whose sum equals the target. Sorted the array initially to efficiently handle duplicates and enable pruning. At each step: ✔️ Skipped duplicate elements using i > n && nums[i] == nums[i-1] ✔️ Stopped recursion early when the current element exceeded the target ✔️ Moved to the next index (i+1) to avoid reusing elements Strengthened my understanding of handling duplicates in recursion and optimizing search space. ⏱ Time Complexity: O(2ⁿ)*k (k is avg length of each combination) 🧠 Space Complexity: O(n) ⚡ Key Takeaways: ✔️ Sorting helps in both pruning and duplicate handling ✔️ Skipping duplicates is crucial for unique combinations ✔️ Backtracking becomes efficient with early stopping conditions 💻 Language Used: Java ☕ 📘 Concepts: Backtracking · Recursion · Arrays · Duplicate Handling · Pruning #CodeEveryday #DSA #LeetCode #Java #Backtracking #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
Day 76/100 Completed ✅ 🚀 Solved LeetCode – Search a 2D Matrix (Java) ⚡ Implemented an optimized binary search approach by treating the 2D matrix as a flattened sorted array. Converted 1D index into 2D coordinates (row = mid / m, col = mid % m) to efficiently locate the target in O(log(m × n)) time. 🧠 Key Learnings: • Applying binary search on a 2D matrix • Converting 1D index to 2D (row & column mapping) • Reducing time complexity from O(m × n) → O(log(m × n)) • Importance of problem observation (matrix behaves like sorted array) 💯 This problem strengthened my understanding of binary search variations and how to apply it beyond simple 1D arrays. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #binarysearch #arrays #optimization #problemSolving #100DaysOfCode 🚀
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
-
-
🚀 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 99/150 — BINARY SEARCH ON ANSWER! 🔥📊 Day 99 of my 150 Days DSA Challenge in Java and today I solved a very important problem that uses Binary Search in a 2D matrix 💻🧠 📌 Problem Solved: Kth Smallest Element in a Sorted Matrix 📌 LeetCode: #378 📌 Difficulty: Medium–Hard 🔹 Problem Insight The task is to find the kth smallest element in an n x n matrix where: • Each row is sorted • Each column is sorted 👉 Instead of flattening and sorting (O(n² log n)), we can do better using Binary Search on Answer. 🔹 Approach Used I used Binary Search on Value Range: • Set: low = smallest element high = largest element • Apply binary search: Find mid Count how many elements are ≤ mid 👉 If count < k → move right (low = mid + 1) 👉 Else → move left (high = mid) ✔️ Continue until low == high → answer found 🔹 Counting Logic (Optimized) • Start from bottom-left corner • If element ≤ mid: All elements above are also ≤ mid Move right • Else: Move up ✔️ This gives O(n) counting per iteration ⏱ Complexity Time Complexity: O(n log (max - min)) Space Complexity: O(1) 🧠 What I Learned • Binary Search is not just for arrays — it can be applied on answer space • Matrix properties can be used for efficient counting • Avoid brute force by leveraging sorted structure 💡 Key Takeaway This problem taught me: How to apply Binary Search on Answer pattern How to optimize 2D problems using structure Thinking beyond direct sorting approaches 🌱 Learning Insight Now I’m improving at: 👉 Recognizing when to use Binary Search beyond arrays 👉 Solving problems with optimized thinking 🚀 ✅ Day 99 completed 🚀 51 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/g-yhc7kH 💡 Don’t search the data — search the answer. #DSAChallenge #Java #LeetCode #BinarySearch #Matrix #Optimization #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
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
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 related topics
- LeetCode Array Problem Solving Techniques
- Leetcode Problem Solving Strategies
- Approaches to Array Problem Solving for Coding Interviews
- Java Coding Interview Best Practices
- Common Algorithms for Coding Interviews
- Strategies for Solving Algorithmic Problems
- Google SWE-II Data Structures Interview Preparation
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