🧠 LeetCode POTD — The Biggest Hint Was Hidden in One Line 1855. Maximum Distance Between a Pair of Values Today's problem looked tricky at first considering the time complexity. We need to find indices (i, j) such that: 👉 i <= j 👉 nums1[i] <= nums2[j] And maximize: 👉 j - i ━━━━━━━━━━━━━━━━━━━ My first instinct? Try brute force combinations. Check many pairs. Maybe binary search. But I was missing the most important line in the question: Both arrays are non-increasing (sorted). That one detail changes everything. ━━━━━━━━━━━━━━━━━━━ 💡 Once I noticed that, the solution became a clean two-pointer approach. Start with: 👉 i = 0 in nums1 👉 j = 0 in nums2 Then: If nums1[i] <= nums2[j] 👉 This pair is valid 👉 Update answer with j - i 👉 Move j forward to try for a bigger distance Else: 👉 Current i is too large 👉 Move i forward Because arrays are sorted, once a pair fails, moving i is the only useful move. ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: The challenge wasn't the coding. It was reading carefully enough to spot the property that unlocks the solution. ✅ Sometimes the answer is already in the problem statement. ✅ You just have to notice it. Curious — did anyone else miss the sorted hint at first? 👀 #LeetCode #TwoPointers #ProblemSolving #SoftwareEngineering #DSA #Java #c++ #SDE
Maximize Distance Between Pair of Values in Sorted Arrays
More Relevant Posts
-
📅 Day 46/100 – LeetCode DSA Challenge 🧩 Problem: Longest Continuous Increasing Subsequence (674) 💡 Problem Summary Find the length of the longest continuous strictly increasing subarray. The sequence must be continuous, not just increasing elements from anywhere. 💡 My Approach I solved this problem by comparing each element with its next element: Initialized: count = 1 → current increasing sequence max = 1 → maximum length Traversed the array till n-1 to safely check nums[i+1] If nums[i] < nums[i+1] → increment count Else → reset count = 1 Continuously updated max using Math.max() This approach ensures we only consider continuous increasing sequences. 🧾 Code: class Solution { public int findLengthOfLCIS(int[] nums) { if(nums.length == 0) return 0; int count = 1; int max = 1; for(int i = 0; i < nums.length - 1; i++) { if(nums[i] < nums[i+1]) { count++; max = Math.max(count, max); } else { count = 1; } } return max; } } 📚 What I Learned How to safely use i+1 by controlling loop boundary Importance of handling edge cases (nums.length == 0) Difference between continuous vs non-continuous sequences Greedy approach for tracking subarray length Writing optimized O(n) solutions 🚀 Small improvements every day lead to big results! #Day46 #100DaysOfCode #LeetCode #DSA #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 31 Today’s focus: Binary Search for boundaries and square roots. Problems solved: • Sqrt(x) (LeetCode 69) • Search Insert Position (LeetCode 35) Concepts used: • Binary Search • Search space reduction • Boundary conditions Key takeaway: In Sqrt(x), the goal is to find the integer square root. Using binary search, we search in the range [1, x] and check mid * mid against x to narrow down the answer. This avoids linear iteration and achieves O(log n) time. In Search Insert Position, we use binary search to find either: • The exact position of the target, or • The correct index where it should be inserted The key idea is that when the target is not found, the final position of the left pointer gives the correct insertion index. These problems highlight how binary search is not just for finding elements, but also for determining positions and boundaries efficiently. Continuing to strengthen fundamentals and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 LeetCode — Problem 242 | Day 14 💡 Problem: Valid Anagram --- 🧠 Problem: Given two strings s and t, return true if t is an anagram of s, otherwise false. --- 🧠 Approach: - First check length: • If lengths differ → not an anagram - Use a frequency array of size 26 - Traverse both strings: • Increment count for s • Decrement count for t - Finally check: • If all values are 0 → valid anagram --- ⚙️ Core Logic: - freq[s.charAt(i) - 'a']++ - freq[t.charAt(i) - 'a']-- 👉 If all counts become zero → both strings have same characters --- ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) (fixed size array) --- ⚠️ Edge Cases: - Different lengths → false - Same characters, different order → true - Completely different strings → false --- 🔍 Insight: Instead of sorting, count character frequency --- 🔑 Key Learning: - Frequency counting is faster than sorting - Fixed-size array gives O(1) space - Simple and optimal approach for character problems --- "Compare frequency of characters using a fixed array instead of sorting." --- #LeetCode #DSA #Java #Strings #CodingJourney
To view or add a comment, sign in
-
-
. 🚀 Day 27/30 – DSA Challenge 📌 LeetCode Problem – Middle of the Linked List 📝 Problem Statement Given the head of a singly linked list, return the middle node of the linked list. 👉 If there are two middle nodes, return the second middle node. 📌 Example Input: 1 → 2 → 3 → 4 → 5 Output: 3 📌 Even Case Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 4 💡 My Approach (Counting Method) Instead of using two pointers, I used a two-step approach: 👉 First count total nodes 👉 Then move to the middle 🚀 Algorithm 1️⃣ Traverse the list and count nodes 2️⃣ Calculate middle index: mid = count / 2 3️⃣ Traverse again till mid position 4️⃣ Return that node ✅ Java Code class Solution { public ListNode middleNode(ListNode head) { int count = 0; ListNode temp = head; // Step 1: Count nodes while (temp != null) { count++; temp = temp.next; } // Step 2: Find middle index int mid = count / 2; // Step 3: Traverse to middle temp = head; for (int i = 0; i < mid; i++) { temp = temp.next; } return temp; } } ⏱ Complexity Time Complexity: O(n) (two traversals) Space Complexity: O(1) 📚 Key Learnings – Day 27 ✔ Problems can have multiple valid approaches ✔ Counting method is simple and intuitive ✔ Always think about optimizing further ✔ Same problem can be solved in one pass using fast & slow pointers Simple idea. Clear logic. Solid understanding. Day 27 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
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
-
-
📘 DSA Journey — Day 33 Today’s focus: Binary Search for next greater element. Problem solved: • Find Smallest Letter Greater Than Target (LeetCode 744) Concepts used: • Binary Search • Upper bound concept • Circular handling Key takeaway: The goal is to find the smallest character strictly greater than a given target in a sorted array. This is a classic upper bound problem: We use binary search to find the first element greater than the target. During search: • If letters[mid] > target, store it as a possible answer and move left • Else move right An important edge case: If no character is greater than the target, we return the first element (circular behavior). Continuing to strengthen binary search patterns and problem-solving consistency. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
“What I learned after solving 300+ LeetCode problems 👇” At the beginning, I made a mistake. I kept solving random problems every day thinking: “More problems = more skill” But I was wrong. I realized that solving problems randomly is mostly a waste of time if you don’t understand the pattern behind them. Everything changed when I started focusing on patterns instead of problems. Here are some important patterns I learned: • Sliding Window • Two Pointers • Prefix Sum • Binary Search • Recursion & Backtracking • Linked List Patterns • Stack & Monotonic Stack • Hashing / Frequency Count Once you understand these patterns: You don’t need to solve 1000 problems. You start recognizing solutions instantly. Now when I see a problem, I don’t panic. I ask: 👉 “Which pattern does this belong to?” That one question changed everything for me. Still learning, but now with direction 🚀 #DSA #LeetCode #Java #BackendDevelopment #CodingJourney
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟯: 𝗣𝗶𝘃𝗼𝘁𝗶𝗻𝗴 𝘄𝗵𝗲𝗻 𝘁𝗵𝗲 𝘀𝗶𝗺𝗽𝗹𝗲 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝗳𝗮𝗶𝗹𝘀. 🧠 The screenshot doesn’t show the struggle, It just shows the final Accepted code. ✅𝗙𝗼𝗿 𝗗𝗮𝘆 𝟯, I tackled this LeetCode problem: "𝟮𝟴𝟯𝟵. 𝗖𝗵𝗲𝗰𝗸 𝗶𝗳 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗖𝗮𝗻 𝗯𝗲 𝗠𝗮𝗱𝗲 𝗘𝗾𝘂𝗮𝗹 𝗪𝗶𝘁𝗵 𝗢𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗜." My goal was simple: just get that Java solution 𝗔𝗰𝗰𝗲𝗽𝘁𝗲𝗱. 𝗧𝗵𝗲 𝗙𝗶𝗿𝘀𝘁 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: I initially started with a classic iterative method, trying to loop through and swap indices to check equality. But I kept hitting unexpected logic errors that were overcomplicating a simple problem. I realized the "obvious" way wasn't the "correct" way. 𝗧𝗵𝗲 𝗣𝗶𝘃𝗼𝘁: Instead of getting stuck on the iteration, I looked at the core constraint. The operation only allows swaps between characters exactly 2 indices apart (e.g., indices 0 and 2, 1 and 3). 𝗧𝗵𝗲 𝗕𝗿𝗲𝗮𝗸𝘁𝗵𝗿𝗼𝘂𝗴𝗵: I realized that if strings are length 4, characters at even indices (0, 2) can only ever interact with each other. The same applies to odd indices (1, 3). So, instead of looping, I just needed to compare those two specific pairs directly. ✅𝗧𝗵𝗲 𝗿𝗲𝘀𝘂𝗹𝘁: I simplified the code into two simple comparison blocks and hit Submit. That final 𝟭𝗺𝘀 𝗥𝘂𝗻𝘁𝗶𝗺𝗲 (𝗕𝗲𝗮𝘁𝗶𝗻𝗴 𝟵𝟵.𝟲𝟲%) was the perfect confirmation that the pivot was the right choice. Sometimes the best engineering decision is to tear down what isn't working and start with a cleaner logic. #Java #JavaDeveloper #DSA #Strings #BuildInPublic #EngineeringStudent #DAY3
To view or add a comment, sign in
-
-
🧠 LeetCode POTD — Simple Problem, One Small Trick 2515. Shortest Distance to Target String in a Circular Array At first glance, this feels very straightforward. 👉 Find all positions of target 👉 Compute distance from startIndex (from both directions) 👉 Take the minimum Done. But then I thought… Why am I finding all positions first? We're allowed to move left or right, one step at a time. ━━━━━━━━━━━━━━━━━━━ 💡 So instead, I started from startIndex and expanded in both directions simultaneously. 📌 The moment we hit the target → that distance is already the minimum. No need to check anything else. ━━━━━━━━━━━━━━━━━━━ The only tricky part? Handling the circular nature of the array. 💡 Clean trick — both directions in the same loop: → Right: (start + i) % n → Left: (start - i + n) % n That's it. ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: Not about complexity. Not about fancy algorithms. Just about finding a clean way to move in both directions. ✅ Sometimes the hardest part isn't solving… ✅ It's writing a simple idea cleanly. Curious if someone approached this differently 👀 #LeetCode #ProblemSolving #SoftwareEngineering #DSA #C++ #Java #SDE
To view or add a comment, sign in
-
-
🚀 Day 11 of Java with DSA Journey — This one blew my mind 🤯 📌 Problem: Power of Three (LeetCode 326) Yesterday, I used bit manipulation for Power of Two. Today? 👉 That approach completely fails. So I had to think differently… 💡 Breakthrough Idea Instead of loops or recursion… I used math + number theory to solve it in O(1) time. 👉 1162261467 % n == 0 Yes, one line. 🧠 Key Learnings 🔹 Bitwise isn’t universal Works great for base-2, but not for base-3 🔹 Prime Numbers Matter Since 3 is prime, its powers divide each other perfectly 🔹 Max Value Trick Largest power of 3 in 32-bit int = 3^19 = 1162261467 ⚡ Complexity ⏱ Time: O(1) 📦 Space: O(1) 🔥 Pro Tips (Interview Level) 💡 Tip 1: Know Your Data Type Limits Many O(1) tricks depend on constraints like 32-bit integer limits 💡 Tip 2: Prime Numbers Unlock Shortcuts If a number is prime, its powers have clean divisibility properties 💡 Tip 3: Always Question the Default Approach Most people write: while (n % 3 == 0) n /= 3; 💡 Tip 4: This is a Pattern Power of 2 → bitwise Power of 3 → math Power of 4 → hybrid 💡 Tip 5: Edge Cases First Always check n <= 0 🔥 Real Insight This problem forced me to shift my thinking: ❌ Rely on one technique ✅ Adapt based on the problem Consistency compounds 📈 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #NumberTheory #InterviewPrep #Day11 #BitManipulation #CleanCode #Array #Optimization #MCA #lnct #100DaysOfCode #SoftwareEngineering #Algorithms #InPlaceAlgorithms #TechLearning #JavaDeveloper
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