🚀 Day 80 of My #100DaysOfLeetCode Journey Problem: 719. Find K-th Smallest Pair Distance Difficulty: Hard 💥 Today I tackled another challenging problem that really tested my ability to optimize beyond brute force. At first, I wrote a simple solution: 👉 Generate all possible pairs 👉 Find their absolute differences 👉 Sort them and return the (k-1)th smallest It worked fine — until the 11th test case 😅 — Time Limit Exceeded (TLE) reminded me that brute force doesn’t scale! Then I explored the efficient approach: 🔹 Sort the array 🔹 Use binary search on the distance range (0 to max diff) 🔹 For each mid distance, use two pointers to count how many pairs have a distance ≤ mid This reduced the time complexity drastically and helped me understand how binary search can be used not only on arrays, but also on the answer space itself! 💡 Key Learnings: Think about what you’re searching for — sometimes the answer itself is the search space. Two-pointer patterns are incredibly powerful when combined with sorted data. Optimization is not just about speed — it’s about clarity and scalability. Every hard problem starts as a puzzle, but once you see the pattern, it becomes a story of logic. #LeetCode #100DaysOfCode #Java #ProblemSolving #BinarySearch #TwoPointers #CodingJourney
Solved 719. Find K-th Smallest Pair Distance with Binary Search
More Relevant Posts
-
#Day_34 Today’s problem was a satisfying one to solve — “Single Element in a Sorted Array” 🔍 Given a sorted array where every element appears twice except for one unique element, the task is to identify that single element. At first, it seems like a simple linear scan could do the job — and yes, it can. But I focused on building a clean and logical O(n) approach before thinking about optimization 🧠 Approach We observe that: Every element appears in pairs, and because the array is sorted, duplicates are adjacent. The unique element is the only one that doesn’t match its left or right neighbor. We can handle three cases: First element: If it’s not equal to the next one → it’s the single element. Last element: If it’s not equal to the previous one → it’s the single element. Middle elements: If an element is different from both its previous and next → that’s our answer. This way, we can detect the single element in just one pass through the array ⏱ Complexity Time: O(n) — We traverse the array once. Space: O(1) — No extra memory used. 💬 Reflection This problem is a good reminder that not every efficient solution has to start complex. Sometimes, the cleanest brute-force version gives a perfect foundation for further optimization — in this case, even leading to an O(log n) binary search variant. Each problem in this challenge pushes me to think deeper about patterns, structure, and clarity in problem-solving. #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode #Java #LearnByDoing #DSA
To view or add a comment, sign in
-
-
🚩 Problem: 169. Majority Element 🔥 Day 43 of #100DaysOfLeetCode 🔍 Problem Summary: Given an array nums, find the element that appears more than ⌊ n/2 ⌋ times. You may assume that the majority element always exists in the array. ✅ Approach 1: Using HashMap Count the frequency of each element using a HashMap and return the one that occurs most frequently. ✅ Approach 2 (Optimized): Boyer–Moore Voting Algorithm Maintain a candidate and count. Traverse the array: If count == 0, set candidate = num. If num == candidate, increment count, else decrement. Return the candidate. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ✨ Key Takeaway: The Boyer–Moore Voting Algorithm is a brilliant example of how a deep understanding of problem constraints can lead to an O(1) space solution — an essential pattern in algorithmic thinking. Link:[https://lnkd.in/gsc4XgbK] #100DaysOfLeetCode #Day43 #Problem169 #MajorityElement #BoyerMoore #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #DataStructures #TechCareers #ArjunInfoSolution #CodingCommunity #CodeNewbie #SoftwareEngineering #ZeroToHero #LearnToCode
To view or add a comment, sign in
-
-
🔥 Day 31/100 of #100DaysOfCode - Linked List Cleanup! Today's Problem: Remove Duplicates from Sorted List Task: Delete all duplicates from a sorted linked list so each element appears only once. Solution: Used a straightforward iterative approach with a single pointer! Traversed the list and whenever the current node's value matched the next node's value, I "skipped" the duplicate by pointing current.next to current.next.next. Key Insights: Since the list is pre-sorted, duplicates are guaranteed to be adjacent Only need one pointer to traverse and remove duplicates in place O(n) time complexity with O(1) space - very efficient! Edge Cases Handled: Empty list (head == null) Single node lists Multiple consecutive duplicates Simple but elegant linked list manipulation! Each problem builds better intuition for pointer operations. 🎯 #100DaysOfCode #LeetCode #Java #DataStructures #LinkedList #Algorithm #CodingJourney
To view or add a comment, sign in
-
-
🧠 LeetCode Day 97 — Path Sum (Problem 112) Today’s challenge was about checking whether a binary tree has a root-to-leaf path such that adding up all the values along the path equals a given sum. 🔍 Problem Description: Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that the sum of the node values equals targetSum. Otherwise, return false. 💡 Approach: Traverse the tree recursively. Subtract the current node’s value from targetSum. When a leaf node is reached, check if the remaining sum equals zero. Use Depth First Search (DFS) to explore all paths. 🚀 Key Learnings: Strengthened understanding of recursive tree traversal. Practiced handling base cases in recursion effectively. Improved clarity on root-to-leaf path logic in binary trees. 🌳 #Day97 of #100DaysOfCode Each challenge adds a new layer to my problem-solving skills. Binary tree problems like this sharpen the recursive mindset — thinking from root to leaf and back up! 💪 #LeetCode #CodingChallenge #Java #100DaysOfCode #BinaryTree #ProblemSolving #Recursion
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 81 Linked List Cycle Problem Given the head of a linked list, determine whether the list contains a cycle meaning a node’s next pointer refers back to a previous node. My Approach Used Floyd’s Cycle Detection Algorithm (Tortoise & Hare Method): Initialized two pointers slow and fast. Moved slow one step and fast two steps in each iteration. If they ever meet → cycle detected. If fast or fast.next becomes null → no cycle exists. Complexity Time: O(n) Space: O(1) Even in problems involving dynamic structures like linked lists, a simple pointer-based approach can lead to an elegant and optimal solution. #100DaysOfCode #LeetCode #Java #ProblemSolving #DataStructures #LinkedList #TortoiseAndHare #takeUforward #CodeNewbie #CodingJourney
To view or add a comment, sign in
-
-
👇 📅 Day 84 of #100DaysOfLeetCode Problem: Find Largest Value in Each Tree Row (LeetCode #515) Approach: The problem requires finding the largest value in each level of a binary tree. This can be efficiently solved using Level Order Traversal (BFS). For each level, store all node values and select the maximum one. Add these maximum values to the result list. Steps: Use a queue to perform level-by-level traversal. For each level, collect node values in a list. Compute the maximum value for that level and add it to the output list. Continue until the queue is empty. Complexity: ⏱️ Time: O(n) — every node is visited once. 💾 Space: O(n) — queue and result storage. 🔗 Problem Link: https://lnkd.in/eQz5GBU8 🔗 Solution Link: https://lnkd.in/eAC_3SwK #LeetCode #100DaysOfCode #BinaryTree #LevelOrderTraversal #BFS #DataStructures #Java #Algorithms #ProblemSolving #DailyCoding #CodingChallenge #BuildInPublic #LearnToCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🔥 Day 33/100 of #100DaysOfCode - Alternating Positive & Negative! Today's Problem: Rearrange Array Elements by Sign Task: Given an array with equal number of positive and negative integers, rearrange them in alternating positive/negative order (starting with positive). Solution: Used a two-pointer approach with separate indices for positive and negative positions! Created a temp array and placed positives at even indices (0, 2, 4...) and negatives at odd indices (1, 3, 5...). Key Insights: Since the array has equal positives and negatives, we can pre-determine positions O(n) time complexity with O(n) space for the temp array Clean and intuitive - no complex swapping needed Smart Pointer Management: Positive pointer moves by +2 each time Negative pointer moves by +2 each time Single pass through the original array Elegant solution for maintaining relative order while achieving the required alternation! ⚡ #100DaysOfCode #LeetCode #Java #Algorithms #Arrays #TwoPointers #CodingInterview
To view or add a comment, sign in
-
-
#Day_27 Today’s problem was an interesting twist on binary search — “Find Peak Element” 🔍 Given an array of numbers, the task is to find an index i such that nums[i] is greater than its neighbors — basically, a peak element. At first glance, it seems like a simple linear scan could solve it in O(n). But I wanted to do better — and that’s where binary search comes in 💡 🧠 Approach We observe that: If nums[mid] > nums[mid + 1], it means we are on a descending slope, so the peak lies on the left side (including mid). Otherwise, we’re on an ascending slope, so the peak lies on the right side (after mid). Using this logic, we can shrink our search space by half in every iteration — a classic divide and conquer move 🔥 ⏱ Complexity Time: O(log n) Space: O(1) This is a great example of how binary search isn’t just for sorted arrays — it can also be applied to problems involving patterns or directional decisions. 💬 Every day of this challenge reinforces that problem-solving isn’t just about writing code — it’s about recognizing patterns, making logical deductions, and applying optimized thinking. #CodingJourney #LeetCode #BinarySearch #ProblemSolving #100DaysOfCode #Java #LearnByDoing
To view or add a comment, sign in
-
-
Day 44 of #50DaysOfLeetCodeChallenge Problem: Add Two Numbers -Approach: Since the digits are stored in reverse, I started adding from the head nodes, just like manual addition from the least significant digit. Maintained a carry for sums ≥ 10. Traversed both lists simultaneously, creating new nodes for each sum digit. If a carry remained at the end, added it as a new node. -Key Takeaways: Linked lists can represent numbers in creative ways. Starting from the least significant digit simplifies addition. Carry handling is crucial for correctness. #LinkedInLearning #CodingJourney #Java #DataStructures #ProblemSolving #Algorithms #LeetCode #50Days
To view or add a comment, sign in
-
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