Most people overcomplicate this problem. I almost did too. 🚀 Day 78/365 — DSA Challenge Find K Closest Elements You're given a sorted array. Pick k elements closest to x. Sounds simple... but there's a catch: You must return them sorted And follow distance rules carefully. 💡 My Approach: Instead of checking every combination... I used a two-pointer shrinking window Start with the full array Then shrink it until only k elements remain At each step: Compare: • distance from start → |arr[start] - x| • distance from end → |arr[end] - x| Remove the one farther from x Repeat until window size = k ⚡ Why this works: We always remove the worst candidate So the remaining window is optimal ⏱ Time: O(n) 📦 Space: O(1) What I learned: Sometimes the solution is not about building... It's about removing smartly Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency
Find K Closest Elements in Sorted Array
More Relevant Posts
-
“Most people try to overcomplicate this one… but the simplest approach wins.” Day 69 — LeetCode Progress Problem: Height Checker Required: Given an array of student heights, return the number of indices where the heights are not in the expected non-decreasing order. Idea: If we sort the array, we get the expected order. Now just compare the original array with the sorted version — mismatches are the answer. Approach: Create a copy of the original array Sort the copied array Traverse both arrays: Compare elements at each index If they differ → increment count Return the count Time Complexity: O(n log n) Space Complexity: O(n) #LeetCode #DSA #Java #Arrays #Sorting #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Many subarray problems follow the same hidden pattern — once you recognize it, they become much easier. 🚀 Day 102/365 — DSA Challenge Solved: Count Number of Nice Subarrays Problem idea: We need to count the number of subarrays that contain exactly k odd numbers. Efficient approach: Use the same trick as previous problem: subarrays with exactly k odds = subarrays with ≤ k odds − subarrays with ≤ (k − 1) odds Steps: 1. Use a sliding window to count subarrays with at most k odd numbers 2. Expand window by moving right pointer 3. If odd count exceeds k, shrink window from left 4. Add valid subarrays ending at each index 5. Subtract results to get exact count This pattern works beautifully for binary-like conditions. ⏱ Time: O(n) 📦 Space: O(1) Day 102/365 complete. 💻 263 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
🔥 Day 364 – Daily DSA Challenge! 🔥 Problem: 🎯 Find K Closest Elements Given a sorted array arr, an integer k, and a target x, return the k closest elements to x in ascending order. 💡 Key Insight — Binary Search on Window Instead of checking each element, we binary search the starting index of a window of size k. Search space: Possible windows → [0 ... n - k] 🧠 Decision Logic At index mid, compare: Distance of left boundary → x - arr[mid] Distance of right boundary → arr[mid + k] - x We choose direction based on: ⚡ Algorithm Steps ✅ Initialize: left = 0, right = n - k ✅ Binary search: If left side is farther → shift right Else → move left ✅ Final window starts at left ✅ Collect k elements ⚙️ Complexity ✅ Time Complexity: O(log(n - k) + k) (binary search + result building) ✅ Space Complexity: O(k) 💬 Challenge for you 1️⃣ Why do we search on window positions instead of elements? 2️⃣ Can you solve this using a heap approach? 3️⃣ What if array was unsorted? #DSA #Day364 #LeetCode #BinarySearch #SlidingWindow #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
Day 42 of Daily DSA 🚀 Solved LeetCode 921: Minimum Add to Make Parentheses Valid ✅ Problem: Given a parentheses string s, return the minimum number of moves required to make it valid. Rules: A valid string has balanced opening and closing brackets You can insert a parenthesis at any position Return the minimum additions needed Approach: Used a Stack + Counter approach to track unmatched parentheses. Steps: Traverse the string Push '(' onto stack If ')' and stack has '(' → pop Else → increment counter (unmatched closing) At the end → remaining stack size = unmatched openings Result = unmatched openings + unmatched closings ⏱ Complexity: • Time: O(n) • Space: O(n) 📊 LeetCode Stats: • Runtime: 1 ms (Beats 67.19%) ⚡ • Memory: 43.08 MB Nice extension of the Valid Parentheses problem, focusing on fixing invalid cases instead of just checking them. #DSA #LeetCode #Java #Stack #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 28 Today’s focus: Binary Search for minimum in rotated arrays. Problem solved: • Find Minimum in Rotated Sorted Array (LeetCode 153) Concepts used: • Binary Search • Identifying unsorted half • Search space reduction Key takeaway: The goal is to find the minimum element in a rotated sorted array. Using binary search, we compare the mid element with the rightmost element: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) This works because the rotation creates one unsorted region, and the minimum always lies in that region. By narrowing the search space each time, we achieve O(log n) time complexity. This problem highlights how slight modifications in array structure still allow binary search to work efficiently with the right observations. Continuing to strengthen binary search patterns and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 47 of Daily DSA 🚀 Solved LeetCode 74: Search a 2D Matrix ✅ Problem: Given a sorted 2D matrix where: • Each row is sorted • First element of each row > last element of previous row Find whether a target exists in the matrix. Approach: Used an optimized staircase search (top-right traversal). Steps: Start from top-right corner If element == target → return true If element > target → move left If element < target → move down Continue until found or out of bounds ⏱ Complexity: • Time: O(n + m) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 43.84 MB Sometimes choosing the right starting point (top-right) makes the search super efficient 💡 #DSA #LeetCode #Java #Matrix #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 36 of my DSA Journey 📌 Problem: 560. Subarray Sum Equals K Given an array and a value k, we need to find how many subarrays (continuous parts of the array) add up to k. 💡 My Approach (Simple Explanation): Instead of checking all subarrays (which is slow), I used the prefix sum + HashMap trick. Keep adding elements to get a running sum Check if (current sum - k) was seen before If yes, it means a valid subarray exists Store prefix sums in a map to reuse quickly This makes the solution efficient ⚡ ✅ Result: Accepted ⏱ Runtime: 0 ms ✨ Small optimizations like this really show how powerful concepts can simplify problems! #Day36 #DSA #CodingJourney #Java #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
Day 37/75 — Letter Combinations of a Phone Number Today’s problem was about generating all possible letter combinations from a digit string (like a phone keypad). Approach: • Use backtracking (recursion) • Map each digit to its corresponding letters • Build combinations step by step • Explore all possible paths Key logic: for (char c : letters.toCharArray()) func(idx + 1, digits, temp + c, result, map); Time Complexity: O(4^n × n) Space Complexity: O(n) recursion stack Key Insight: Not every exponential problem is bad — here we must generate all combinations, so complexity is output-dependent. 37/75 🚀 #Day37 #DSA #Backtracking #Java #Algorithms #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 48/60 - DSA Challenge Today’s problem was about finding the minimum number of days required to make bouquets 🌸 🔍 Key Insight: Each bouquet requires k consecutive flowers, and each flower blooms on a specific day. The challenge is to determine the earliest day when we can make at least m bouquets. ⚡ Approach: First, check if it’s even possible to make the required bouquets Use Binary Search on days instead of iterating day by day For a given day, count how many bouquets can be formed If we can make enough bouquets, try for a smaller day Otherwise, increase the number of days 📈 Time Complexity: O(n log range) 📦 Space Complexity: O(1) 💡 This problem beautifully demonstrates how Binary Search isn’t just for arrays—it can be applied on answers (search space) to optimize brute-force solutions. 🔥 Another step forward in mastering DSA and problem-solving patterns! #Day48 #DSA #BinarySearch #CodingJourney #Java #ProblemSolving #LeetCode #100DaysOfCode
To view or add a comment, sign in
-
-
🔥 Day 356 – Daily DSA Challenge! 🔥 Problem: ⚡ Max Consecutive Ones III Given a binary array nums and an integer k, return the maximum number of consecutive 1s if you can flip at most k zeros. 💡 Key Insight — Sliding Window We maintain a window where the number of zeros is at most k. Core condition: 🧠 How It Works 🔹 Expand the window using right 🔹 Count zeros in the window 🔹 If zeros exceed k → shrink from left 🔹 At every step, window length is a valid answer ⚡ Algorithm Steps ✅ Initialize: left = 0, zero = 0, max = 0 ✅ Traverse with right: If nums[right] == 0 → increment zero While zero > k: shrink window from left Update max length ⚙️ Complexity ✅ Time Complexity: O(n) (each element processed once) ✅ Space Complexity: O(1) 💬 Challenge for you 1️⃣ Why does this work only for binary arrays? 2️⃣ How would you modify this for longest substring with at most k distinct characters? 3️⃣ What if we want to flip exactly k zeros instead of at most k? #DSA #Day356 #LeetCode #SlidingWindow #TwoPointers #Arrays #Java #ProblemSolving #KeepCoding
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