🔥 Day 84 of #100DaysOfCode Today’s problem: LeetCode: Find K Closest Elements 🎯 📌 Problem Summary Given: A sorted array arr An integer k A target value x Return the k closest integers to x in the array. The result must be sorted in ascending order. Example: arr = [1,2,3,4,5], k = 4, x = 3 Output → [1,2,3,4] 🧠 Approach: Two Pointers Shrinking Window Since the array is already sorted, we can: Start with: l = 0 r = arr.length - 1 While the window size is bigger than k: Compare distances: |x - arr[l]| |x - arr[r]| Remove the element that is farther from x ⚙️ Core Idea: while (r - l >= k): if left is closer: r-- else: l++ Finally, return elements from l to r. ⏱ Time Complexity: O(n - k) 💾 Space Complexity: O(1) (excluding result list) 🚀 Performance ⚡ Runtime: 4ms (98% faster) Solid optimization using the sorted property of the array. 💡 What I Learned When array is sorted → always think Two Pointers. Instead of building result, shrink unnecessary elements. Cleaner logic often gives better performance. Consistency > Motivation. On to Day 85 🔥 #100DaysOfCode #LeetCode #TwoPointers #Java #DSA #CodingJourney #InterviewPrep
Dinesh Kolhe’s Post
More Relevant Posts
-
🔥 Day 97 of #100DaysOfCode Today’s problem: LeetCode – Search in Rotated Sorted Array 🔄🔍 📌 Problem Summary You are given a rotated sorted array and a target. Your task is to return the index of the target if it exists; otherwise return -1. Example: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 🧠 Approach Used: Linear Search In this solution, we simply iterate through the array and check if the current element equals the target. ⚙️ Logic for(int i = 0; i < nums.length; i++){ if(nums[i] == target){ return i; } } return -1; 💡 Explanation Traverse the array from start to end If the target is found → return the index If the loop finishes → return -1 ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Memory: 43.68 MB 🧠 Learning This problem can also be solved using Binary Search in O(log n) by identifying which half of the rotated array is sorted. But for smaller inputs or quick validation, linear scan works correctly and is simple to implement. Only 3 days left to complete the #100DaysOfCode challenge 🚀 Consistency is the real win here! On to Day 98 🔥 #100DaysOfCode #LeetCode #Java #DSA #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
🔥 Day 98 of #100DaysOfCode Today’s challenge: LeetCode – Search in Rotated Sorted Array II 🔄🔍 📌 Problem Summary You are given a rotated sorted array that may contain duplicates. Your task is to determine whether a target exists in the array. Example: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true 🧠 Approach Used: Linear Search In this implementation, we simply iterate through the array and check if the element matches the target. ⚙️ Logic for(int i = 0; i < nums.length; i++){ if(nums[i] == target){ return true; } } return false; 💡 Explanation Traverse the array from start to end If the target is found → return true If the loop finishes → return false ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Memory: 44.9 MB 🧠 Learning This problem is a variation of Search in Rotated Sorted Array, but with duplicates allowed. While a Binary Search solution exists, duplicates can break the strict ordering and make the logic more complex. A simple linear scan ensures correctness in all cases. Only 2 days left to complete #100DaysOfCode 🚀 Almost at the finish line! On to Day 99 🔥 #100DaysOfCode #LeetCode #Java #DSA #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 523 of #750DaysOfCode 🚀 📌 Problem Solved: Check if Binary String Has at Most One Segment of Ones (LeetCode 1784) 🔎 Problem Summary: Given a binary string s (without leading zeros), we need to check whether the string contains at most one contiguous segment of 1s. If the 1s appear in more than one separate segment, we return false. (LeetCode) 💡 Key Insight: Since the string starts with 1, the only valid structure is: 111...000... If we ever encounter the pattern "01", it means a 1 appeared again after a 0, which creates multiple segments of ones. (AlgoMonster) ⚙️ Approach: Traverse the string or simply check if "01" exists. If "01" is found → more than one segment → return false. ⏱ Complexity: Time: O(n) Space: O(1) 📚 Takeaway: Sometimes string problems become much easier when we identify patterns instead of counting segments. Consistency > Motivation. On to Day 524 tomorrow. 💪 #LeetCode #Java #DataStructures #Algorithms #CodingChallenge #Consistency #ProblemSolving #100DaysOfCode #750DaysOfCode
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 4 Problem: 1582. Special Positions in a Binary Matrix Topic: Array, Matrix 🧠 Approach (Simple Thinking): 🔹 A position is special only if it holds a 1 that is alone in its entire row AND its entire column 🔹 Checking row and column for every cell separately is slow and repetitive 🔹 So we pre-compute rowSum and colSum in one pass before making any decisions 🔹 rowSum[i] == 1 means no other 1 exists in that row 🔹 colSum[j] == 1 means no other 1 exists in that column 🔹 If mat[i][j] == 1 and both sums equal 1 — that's your special position 🔹 Preprocessing once and reusing is the real trick here ⏱️ Time Complexity: Two passes through the full matrix → O(m × n) Every cell is visited exactly twice, nothing more 📦 Space Complexity: Two small arrays for row and column sums → O(m + n) No recursion, no extra grid, just two lightweight arrays doing all the work I wrote a full breakdown with dry run, analogy and step by step code walkthrough here: https://lnkd.in/gFgQxQRP If you approached this differently or have a cleaner way to think about it, drop it in the comments — always curious to see different perspectives 💬 See you in the next problem 👋 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
To view or add a comment, sign in
-
-
🚀 Day 78 / 100 – LeetCode Daily Challenge 🧠 Problem: Triconic Subarray Maximum Sum 📅 Date: March 7, 2026 🏆 Runtime: 3 ms | Beats 99.94% 📦 Memory: 95.28 MB | Beats 46.16% 📝 Problem Insight Today’s challenge was to find the maximum sum of a triconic subarray – a sequence that first decreases, then increases, and finally decreases again. It’s like a "mountain" with two peaks and one valley in between, but in a specific order: down → up → down. This is a more complex variant of the classic mountain or bitonic subarray problems. It requires careful scanning of the array to detect valid triconic patterns and compute their sums efficiently. 💡 My Approach I used a two-pointer expansion method: Iterate through the array and treat each index as a potential peak or valley. Expand left and right while the pattern matches the triconic property. Keep track of the maximum sum encountered. Although the code snippet is incomplete here, the full solution involves: Precomputing left and right decreasing/increasing trends. Validating the three-phase pattern for each possible center. Avoiding redundant computations to keep the time complexity close to O(n). 📊 Results ✅ 861 / 861 test cases passed ⚡ Runtime: 3 ms (beats 99.94% of Java submissions) 📈 Memory: 95.28 MB (beats 46.16%) 🧠 Key Takeaway Pattern recognition problems like this one are great for sharpening your array traversal logic and understanding how to break down complex patterns into manageable checks. The challenge is not just in finding the sum, but in ensuring the pattern holds throughout. 🔗 Let’s Connect! I’m documenting my #100DaysOfCode journey every day – follow along for more problem-solving insights, optimizations, and LeetCode grind! 💻⚡ #LeetCode #Java #CodingChallenge #100DaysOfCode #Day78 #TriconicArray #ProblemSolving #TechJourney #SoftwareEngineering #Algorithms #DataStructures #CodeNewbie #DevCommunity #Programming
To view or add a comment, sign in
-
-
Day 3 of my #30DayCodeChallenge: Handling "Infinite" Numbers! The Problem: Multiply Strings. The Logic: I went back to the basics-literally back to grade school. Since I couldn't rely on the * operator for these massive strings, I simulated the Long Multiplication algorithm: Digit-by-Digit: I broke the strings down, converted characters to integers, and multiplied them one by one. The Index Secret: The product of digits at positions i and j always lands at index (i+j+1). The Carry Phase: I handled the carries in a separate pass to keep the code clean and readable ensuring every digit remains between O and 9. Optimization Highlight: Using a StringBuilder for the final conversion instead of simple String concatenation. This avoids creating multiple immutable String objects in memory, keeping the time complexity at O(m x n). Small steps every day lead to big results. Onward to Day 4! #Java #CodingChallenge #ProblemSolving #Algorithms #StringManipulation #SoftwareDevelopment #150DaysOfCode
To view or add a comment, sign in
-
-
Day 29/30 – LeetCode streak Problem: Fancy Sequence You need to support 'append', 'addAll', 'multAll', and 'getIndex' under modulo '(10^9 + 7)' in 'O(1)' per operation. Core idea Keep the logical sequence implicitly via a global affine transform: * Store an internal array 'vals[]'. * Maintain global coefficients 'mul = a' and 'add = b' so that for every index 'i': 'real_i ≡ a · vals[i] + b (mod M)' * Initially, 'a = 1' and 'b = 0', so the stored value equals the real value. Operations * 'append(val)' We want to store a value 'x' such that: 'a · x + b ≡ val (mod M)' Rearranging gives: 'x ≡ (val − b) · a⁻¹ (mod M)' Since 'M' is prime and 'a ≠ 0', the modular inverse 'a⁻¹' exists and can be computed using Fermat’s little theorem. * 'addAll(inc)' Adding a constant to every element changes the transform: 'a · x + b → a · x + (b + inc)' So we simply update: 'add = (add + inc) % MOD'. * 'multAll(m)' Multiplying every element scales both coefficients: 'a · x + b → (a · m) · x + (b · m)' So update: 'mul = (mul * m) % MOD' 'add = (add * m) % MOD'. * 'getIndex(idx)' If the index is out of range return '-1'. Otherwise compute the real value using the stored transform: 'real = (mul * vals[idx] + add) % MOD'. Day 29 takeaway: Instead of updating every element on each operation, using a lazy affine transformation 'a · x + b' lets you represent the entire sequence with just two parameters, turning what would normally be 'O(n)' updates into constant-time operations. #leetcode #dsa #java #math #design #consistency
To view or add a comment, sign in
-
-
🚀 Day 1/180: Kicking off my DSA Journey! Today’s focus: LeetCode 283 – Move Zeroes. 📝 The Challenge Given an integer array nums, the goal is to shift all the 0s to the end while keeping the non-zero elements strictly in their original order. ⚠️ The Catch: This must be done in-place (no extra memory allowed). 📌 Example Input: nums = [0, 1, 0, 3, 12] Output: [1, 3, 12, 0, 0] Explanation: The zeros are pushed to the back, while 1, 3, 12 stay in their exact original sequence. 💡 First Thoughts The brute-force way out? Just create a secondary array, dump the non-zero numbers in first, and pad the rest with zeros. But that directly violates the $O(1)$ space constraint. The real puzzle was figuring out how to achieve this by only modifying the original array. ⚙️ The Solution: Two-Pointer Technique To optimize the solution, I utilized the Two-Pointer method: Pointer i acts as the explorer, traversing the array. Pointer j acts as an anchor, tracking where the next non-zero element belongs. The Steps: Start j at index 0. Loop through the array with i. Whenever i finds a non-zero number, swap it with nums[j] and bump j up by 1. 🧠 Why It Works Because j only steps forward when a non-zero element is securely locked into place, the original relative order is perfectly preserved. As the non-zeroes move to the front, the zeros naturally get pushed to the back. Zero extra data structures, just a single pass! 📊 Complexity Time Complexity: $O(n)$ — We only traverse the array once. Space Complexity: $O(1)$ — Everything is modified completely in-place. 🔑 Takeaways The Two-Pointer strategy is an absolute lifesaver for tricky array manipulations. "In-place modification" and "preserving relative order" are incredibly common technical interview constraints. Small problems are the best way to test and solidify your core fundamentals. Consistency beats motivation! 💪 Let's build these skills one problem at a time. #100DaysOfCode #DSA #LeetCode #Java #ProblemSolving #InterviewPreparation #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 20 of #100DaysOfCode Solved 54. Spiral Matrix on LeetCode 🌀 🧠 Key insight: Spiral traversal is all about maintaining boundaries. By shrinking the top, bottom, left, and right limits after each pass, we can cover every element exactly once. ⚙️ Approach: 🔹Maintain four pointers: top, down, left, right 🔹Traverse: 🔹Left → Right (top row) 🔹Top → Bottom (right column) 🔹Right → Left (bottom row) 🔹Bottom → Top (left column) 🔹Update boundaries after each traversal ⏱️ Time Complexity: O(m × n) 📦 Space Complexity: O(1) (excluding output list) #100DaysOfCode #LeetCode #DSA #Matrix #Java #ProblemSolving #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 44 / 100 | Subsets Intuition: The task is to generate all possible subsets of a given array. Each element has two choices: either include it in the subset or exclude it. By exploring every possible combination of these choices, we can generate all subsets. Backtracking helps us build subsets step by step and explore all possibilities. Approach: O(n * 2^n) Start with an empty subset. Use backtracking to explore all subset combinations. At each step, add the current subset to the result list. Iterate through the remaining elements of the array. Include the current element in the subset and move forward recursively. After recursion, remove the element (backtrack) to explore other possibilities. Continue this process until all subsets are generated. Complexity: Time Complexity: O(n * 2^n) Space Complexity: O(n) #100DaysOfCode #Java #DSA #LeetCode #Backtracking
To view or add a comment, sign in
-
Explore related topics
- LeetCode Array Problem Solving Techniques
- Leetcode Problem Solving Strategies
- Solving Sorted Array Coding Challenges
- Why Use Coding Platforms Like LeetCode for Job Prep
- How to Improve Array Iteration Performance in Code
- Prioritizing Problem-Solving Skills in Coding Interviews
- Strategies for Solving Algorithmic Problems
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