📌 Median of Two Sorted Arrays Platform: LeetCode #4 Difficulty: Hard ⚙️ Approach • Apply binary search on the smaller array for efficiency • Define search space from 0 to n1 • Partition both arrays such that: – Left half contains (n1 + n2 + 1) / 2 elements – Right half contains remaining elements • Identify boundary elements: – l1, l2 → left side elements – r1, r2 → right side elements • Check valid partition: – l1 <= r2 and l2 <= r1 • If valid: – For even length → median = average of max(left) and min(right) – For odd length → median = max(left) • If not valid: – If l1 > r2, move left – Else move right 🧠 Logic Used • Binary Search on partition index • Dividing arrays into balanced halves • Handling edge cases using boundary values • Achieving optimal O(log(min(n1, n2))) time complexity 🔗 GitHub: https://lnkd.in/g_3x55n8 ✅ Day 36 Completed – Revised advanced binary search and partition-based problem. #100DaysOfCode #Java #DSA #ProblemSolving #CodingJourney #Algorithms #DataStructures #LeetCode #CodingPractice #CodeEveryDay #BinarySearch #ArrayProblems
Median of Two Sorted Arrays - Binary Search Approach
More Relevant Posts
-
🌲 Day 38/75: Measuring the Diameter of a Binary Tree! Today’s LeetCode challenge was a step up in complexity: finding the Diameter of a Binary Tree. The diameter is the length of the longest path between any two nodes in a tree, which may or may not pass through the root. The Strategy: This problem is tricky because the longest path isn't always just the height of the left side plus the height of the right side at the root. It could be tucked away in one of the subtrees! I used a recursive Depth-First Search (DFS) that performs two tasks at once: Calculates Height: It returns the height of the current subtree to its parent. Updates Diameter: It calculates the path passing through the current node (leftHeight + rightHeight) and updates a global diameter variable if this path is the longest found so far. Performance: ✅ Runtime: 1 ms ✅ Complexity: $O(n)$ Time | $O(h)$ Space It’s a great example of how to extract multiple pieces of information from a single recursive pass. One more day closer to the 40-day mark! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #Algorithms #DataStructures #TechJourney
To view or add a comment, sign in
-
-
💡 Day 56 of LeetCode Problem Solved! 🔧 🌟 Mirror of an Integer 🌟 🔗 Solution Code: https://lnkd.in/gvaEY4Sw 🧠 Approach: • Digit Extraction & Reversal Extract digits from right to left using modulo (% 10) and rebuild the reversed number dynamically. • Calculate the absolute difference abs(n - reversed) at the end to find the mirror distance. ⚡ Key Learning: • Mastering number manipulation with fundamental math operators (% and /) is a game-changer for processing integers efficiently without relying on space-consuming String conversions. ⏱️ Complexity: • Time: O(log₁₀(n)) (proportional to the number of digits) • Space: O(1) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #MathLogic #DataStructures
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
🧠 Day 37 / 100 – DSA Practice Solved Multiply Strings on LeetCode ✖️🔢✅ 🔹 Problem: Multiply two non-negative numbers given as strings without using built-in big integer libraries. 🔹 Approach: Simulated the manual multiplication method: Multiply each digit of num1 with each digit of num2 Store results in an array Handle carry properly Build final string while skipping leading zeros 🔍 Key Insight: Using an array of size m + n helps manage positions just like pen-and-paper multiplication 🔹 Complexity: ⏱ Time → O(m × n) 📦 Space → O(m + n) 💯 Result: ✔️ All test cases passed ⚡ Runtime: 3 ms (Beats 85%) Loved implementing this classic math-based approach without using built-in shortcuts 🚀 #Day37 #100DaysOfCode #LeetCode #Java #DSA #Strings #Algorithms #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
💡 Day 57 of LeetCode Problem Solved! 🔧 🌟 Maximum Distance Between a Pair of Values 🌟 🔗 Solution Code: https://lnkd.in/gSP_QePE 🧠 Approach: • Two-Pointer Strategy: Maintain two indices (i for nums1 and j for nums2) to scan both non-increasing arrays in a single efficient pass. • Greedy Search: If nums1[i] <= nums2[j], calculate j - i and expand j to find the maximum possible distance. If the value in nums1 is too large, move i forward. ⚡ Key Learning: • Leveraging the non-increasing nature of arrays with two pointers eliminates the need for nested loops, reducing complexity from O(N^2) to linear O(N+M). ⏱️ Complexity: • Time: O(n + m) • Space: O(1) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #Algorithms #TwoPointers
To view or add a comment, sign in
-
-
Day 12 of #100DaysOfCode — Sliding Window Today, I worked on the problem “Max Consecutive Ones III” LeetCode. Problem Summary Given a binary array, the goal is to find the maximum number of consecutive 1s if you can flip at most k zeros. Approach At first glance, this problem looks like a brute-force or restart-based problem, but the optimal solution lies in the Sliding Window technique. The key idea is to maintain a window [i, j] such that: The number of zeros in the window does not exceed k Expand the window by moving j Shrink the window by moving i whenever the constraint is violated Instead of restarting the window when the condition breaks, we dynamically adjust it. Key Logic Traverse the array using pointer j Count the number of zeros in the current window If zeros exceed k, move pointer i forward until the window becomes valid again At every step, update the maximum window size Why This Works This approach ensures: Each element is processed at most twice Time Complexity: O(n) Space Complexity: O(1) The most important learning here is understanding how to dynamically adjust the window instead of resetting it, which is a common mistake while applying sliding window techniques. In sliding window problems, always focus on expanding and shrinking the window efficiently rather than restarting the computation. #100DaysOfCode #DSA #SlidingWindow #LeetCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
Day 51 of Daily DSA 🚀 Solved LeetCode 83: Remove Duplicates from Sorted List ✅ Problem: Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Approach: Used a single pointer traversal since the list is already sorted, making duplicate detection straightforward. Steps: Start from head node Compare current node with next node If values are same → skip next node Else move current pointer forward Continue until end of list Return updated head ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 45.48 MB Sorted input often simplifies the logic — duplicates become adjacent and easy to remove. #DSA #LeetCode #Java #LinkedList #CodingJourney #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
Day 2/30 — DSA Challenge 🚀 Problem: Lowest Common Ancestor of Deepest Leaves Topic: Tree + DFS Difficulty: Medium Approach: Used DFS to calculate depth of left and right subtrees At each node, compared depths: If equal → current node is LCA Else → return deeper subtree result Mistake / Challenge: Initially overcomplicated thinking about storing all deepest nodes Realized we don’t need to track nodes explicitly, depth comparison is enough Fix: Returned a Pair (node, depth) from recursion Handled everything in one DFS traversal Key Learning: Tree problems often look complex but can be simplified with recursion Focus on what needs to be returned from each call Time Taken: 60 minutes Consistency check ✅ See you on Day 3. GitHub Repo: https://lnkd.in/g87geK_g #DSA #LeetCode #Java #Trees #Recursion #LearningInPublic
To view or add a comment, sign in
-
-
Consistency is starting to compound 💻🌱🔥 Solved another problem today—this time from Binary Trees 🌳🚀 Completed Root to Leaf Paths with 100% accuracy (1115/1115 test cases passed) 💯✅ 🔍 Problem Insight: The task was to return all possible paths from the root node to every leaf node in a binary tree 🌳➡️🍃 🧠 My Approach: 👉 Used DFS (Depth-First Search) with recursion 🔁 👉 Maintained a currentPath list to track nodes while traversing 🛤️ 👉 At each node, added the current value to the path ➕ 👉 If a leaf node was reached, stored a copy of the current path in the final answer 📌 👉 Used backtracking by removing the last node after returning from recursion 🔙 ✨ Why this approach works well: ✔ Natural fit for tree traversal 🌳 ✔ Explores every root-to-leaf path efficiently 🚀 ✔ Backtracking keeps memory controlled 🧠 ✔ Clean recursive structure and easy to follow 🧼 📊 Complexity: ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(h) recursion stack (plus output space for storing all paths) 📦 💡 Key Takeaway: Tree problems become much simpler when you think in terms of: 👉 traversal pattern 👉 path tracking 👉 backtracking DFS + recursion continues to be one of the cleanest ways to solve path-based tree problems 🎯🌳 One more problem solved, one more concept strengthened 💪📈🔥 #BinaryTree #Trees #Recursion #DFS #Java #DataStructures #DSA #ProblemSolving #CodingJourney #100DaysOfCode #SoftwareEngineering #Programming #TechGrowth 💻🌳🚀
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