🚀 Day 21/40 – DSA Challenge 📌 LeetCode Problem – Median of Two Sorted Arrays 📝 Problem Statement Given two sorted arrays nums1 and nums2, find the median of the combined array. 📌 Example Input: nums1 = [1,2] nums2 = [3,4] Output: 2.5 💡 My Approach Instead of using complex binary search, I followed a simple and reliable method: 👉 Merge both arrays 👉 Sort the merged array 👉 Find the median This approach is easy to understand and implement. 🚀 Algorithm 1️⃣ Create a new array of size n1 + n2 2️⃣ Copy elements of both arrays 3️⃣ Sort the merged array 4️⃣ If length is odd → return middle element 5️⃣ If even → return average of two middle elements ✅ Java Code import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] merged = new int[n1 + n2]; for (int i = 0; i < n1; i++) { merged[i] = nums1[i]; } for (int i = 0; i < n2; i++) { merged[n1 + i] = nums2[i]; } Arrays.sort(merged); int n = merged.length; if (n % 2 == 1) { return merged[n / 2]; } else { return (merged[n / 2 - 1] + merged[n / 2]) / 2.0; } } } ⏱ Complexity Time Complexity: O((n + m) log(n + m)) Space Complexity: O(n + m) 📚 Key Learnings – Day 21 ✔ Simple solutions are often easiest to implement ✔ Always understand problem constraints ✔ This problem can be optimized further using binary search ✔ Multiple approaches exist — choose based on context Simple approach. Clear logic. Strong understanding. Day 21 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
Median of Two Sorted Arrays Solution in Java
More Relevant Posts
-
. 🚀 Day 27/40 – 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 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 31/40 – DSA Challenge 📌 LeetCode Problem – Mirror Distance of an Integer 📝 Problem Statement Given an integer n, compute its mirror distance: | n - reverse(n) | Where reverse(n) is formed by reversing the digits of n. 📌 Example Input: n = 25 Output: 27 Explanation: reverse(25) = 52 |25 - 52| = 27 💡 Key Insight The main task is correctly reversing the number. 👉 Extract digits one by one 👉 Build the reversed number ⚠️ Important: Do not lose the original value of n while reversing. 🚀 Algorithm 1️⃣ Store original value 2️⃣ Reverse the number using modulo and division 3️⃣ Return absolute difference ✅ Java Code (Correct & Safe) class Solution { public int mirrorDistance(int n) { int original = n; int reversed = 0; while (n != 0) { int digit = n % 10; reversed = reversed * 10 + digit; n /= 10; } return Math.abs(original - reversed); } } ⏱ Complexity Time Complexity: O(d) (d = number of digits) Space Complexity: O(1) ⚠️ Common Mistake (You Had This Earlier) return Math.abs(n - reversed); ❌ 👉 Because n becomes 0 after the loop ✔ Fix: return Math.abs(original - reversed); ✅ 📚 Key Learnings – Day 31 ✔ Preserve original values during transformations ✔ Digit extraction using % and / is fundamental ✔ Small mistakes can break correct logic ✔ Always dry run with simple inputs Simple problem. Careful implementation. Bug fixed, concept clear. Day 31 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Math #LeetCode
To view or add a comment, sign in
-
-
🚀 LeetCode Problem of the Day 📌 Problem: Minimum Distance to Target Element Given an integer array nums (0-indexed) and two integers target and start, we need to find an index i such that: nums[i] == target |i - start| is minimized 👉 Return the minimum absolute distance. 💡 Key Idea: We simply scan the array and track the minimum distance whenever we find the target. 🧠 Approach Traverse the array Whenever nums[i] == target, compute abs(i - start) Keep updating the minimum result 💻 Java Solution class Solution { public int getMinDistance(int[] nums, int target, int start) { int res = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { res = Math.min(res, Math.abs(i - start)); } } return res; } } 📊 Complexity Analysis ⏱ Time Complexity: O(n) → single pass through the array 🧠 Space Complexity: O(1) → no extra space used ⚡ Simple linear scan, optimal solution — sometimes brute force is already the best solution! #LeetCode #Coding #Java #ProblemSolving #DataStructures #Algorithms #InterviewPrep
To view or add a comment, sign in
-
-
🚀 DAY 94/150 — CONNECTING TREE LEVELS! 🌳🔗 Day 94 of my 150 Days DSA Challenge in Java and today I solved a very interesting problem that focuses on level connections in Binary Trees 💻🧠 📌 Problem Solved: Populating Next Right Pointers in Each Node 📌 LeetCode: #116 📌 Difficulty: Medium 🔹 Problem Insight The task is to connect each node’s next pointer to its right node on the same level. If there is no right node → set next = null. 👉 This problem is based on a perfect binary tree, which allows some optimizations. 🔹 Approaches Used ✅ Approach 1: BFS (Level Order Traversal) • Use a queue to traverse level by level • Connect nodes within the same level using a prev pointer ✔️ Easy to understand ❌ Uses extra space (queue) ✅ Approach 2: Optimized (Constant Space) • Use already established next pointers • Connect: left → right right → next.left ✔️ No extra space (O(1)) ✔️ More optimized and elegant ⏱ Complexity Time Complexity: O(n) Space Complexity: • BFS → O(n) • Optimized → O(1) 🧠 What I Learned • Same problem can have multiple approaches (basic → optimized) • Perfect binary tree structure helps reduce complexity • Using existing pointers smartly can eliminate extra space 💡 Key Takeaway This problem taught me: How to connect nodes level-wise Difference between BFS vs pointer-based optimization Writing space-efficient solutions 🌱 Learning Insight Now I’m focusing more on: 👉 Moving from brute-force → optimized solutions 🚀 ✅ Day 94 completed 🚀 56 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gDWj7K5Q 💡 Optimization is about using what you already have. #DSAChallenge #Java #LeetCode #BinaryTree #BFS #DFS #Pointers #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
📅 Date: April 27, 2026 Day 6 of my LeetCode Journey 🚀 ✅ Problem Solved: 14. Longest Common Prefix 🧠 Approach & Smart Solution: To solve this problem, I used a highly efficient Horizontal Scanning technique. Instead of comparing characters index by index across all strings, I assumed the very first string was the common prefix. Then, I iteratively compared it with the next strings, shaving off characters from the end until a match was found. By leveraging Java's built-in startsWith() method, the logic is kept clean and readable! • Pseudo-code: Assume the first string in the array is the initial 'prefix'. Loop through the rest of the strings in the array: While the current string does not start with the 'prefix': Shorten the 'prefix' by removing its last character. If the 'prefix' becomes completely empty, return "" (no common prefix exists). Return the final 'prefix' after checking all strings. This step-by-step reduction ensures we only do as much work as absolutely necessary. ⏱️ Time Complexity: O(S) (where S is the sum of all characters in all strings) 📦 Space Complexity: O(1) (Only modifying the prefix string, no extra arrays used) 📊 Progress Update: • Streak: 5 Days 🔥 • Difficulty: Easy • Pattern: String / Horizontal Scanning 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Smartly utilizing built-in string methods like startsWith and substring can drastically reduce code complexity! 💡 #LeetCode #DSA #Strings #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
Today I solved the problem: "Closest Target in Circular Array" 🔍 Problem Statement: Given an array of words and a starting index, find the shortest distance to a target word in a circular array. 💡 Key Idea: Since the array is circular, we must consider: ➡️ Direct distance ➡️ Circular distance 👉 Final distance = min(|i - startIndex|, n - |i - startIndex|) 🧑💻 My Optimized Java Solution: class Solution { public int closestTarget(String[] words, String target, int startIndex) { int n = words.length; int minDistance = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (words[i].equals(target)) { int dist = Math.abs(i - startIndex); int circularDist = Math.min(dist, n - dist); minDistance = Math.min(minDistance, circularDist); } } return minDistance == Integer.MAX_VALUE ? -1 : minDistance; } } 📈 What I Learned: How to handle circular array problems 🔄 Importance of optimizing brute-force solutions Writing clean and efficient code for interviews 🔥 Consistency is the key — one problem at a time! #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
🧠 Day 26/75: Logic over Luck When you see a problem that asks for $O(\log n)$ time, your mind should immediately jump to Binary Search. But what if the data isn't perfectly sorted? Today’s LeetCode problem—Search in Rotated Sorted Array—is all about conditions. My approach in Java: Calculate mid safely. Determine if the left half is sorted (nums[left] <= nums[mid]). If yes, check if the target is in that range; otherwise, search the right. If no, it means the right half must be sorted. Result? 0ms Runtime and another problem checked off the list. ✅ Day 26 complete. Every problem is a lesson in thinking more clearly. See you for Day 27! 💻🔥 #Consistency #CodingJourney #LeetCodeChallenge #JavaDeveloper #TechGrowth #100DaysOfCode
To view or add a comment, sign in
-
-
#CodeEveryday — My DSA Journey | Day 2 🧩 Problem Solved: Combination Sum II (LeetCode) 💭 What I Learned: Used backtracking to generate all unique combinations whose sum equals the target. Sorted the array initially to efficiently handle duplicates and enable pruning. At each step: ✔️ Skipped duplicate elements using i > n && nums[i] == nums[i-1] ✔️ Stopped recursion early when the current element exceeded the target ✔️ Moved to the next index (i+1) to avoid reusing elements Strengthened my understanding of handling duplicates in recursion and optimizing search space. ⏱ Time Complexity: O(2ⁿ)*k (k is avg length of each combination) 🧠 Space Complexity: O(n) ⚡ Key Takeaways: ✔️ Sorting helps in both pruning and duplicate handling ✔️ Skipping duplicates is crucial for unique combinations ✔️ Backtracking becomes efficient with early stopping conditions 💻 Language Used: Java ☕ 📘 Concepts: Backtracking · Recursion · Arrays · Duplicate Handling · Pruning #CodeEveryday #DSA #LeetCode #Java #Backtracking #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
Solved Find Peak Element -> LeetCode(162) Medium, Binary Search in Java. Till now I had solved around 10-11 binary search problems. But in all of them array was always sorted , even rotated ones had at least one sorted half. So I had one strong assumption , binary search only works on sorted arrays. This problem broke that assumption completely. No sorted half, no rotation logic working. I was stuck because none of my previous patterns were fitting here. Took help from Claude. It suggested slope based thinking , if right neighbour is greater, peak is on right side, go right. If left neighbour is greater, go left. If both neighbours are smaller, current element is peak. Then I questioned > what if slope breaks in between? Claude pointed me to re-read the problem. The key insight was that array has -∞ at both ends virtually, which guarantees at least one peak always exists. Applied my own logic from there and got it accepted Then Claude showed me a cleaner version , when low < high, at the point where low == high we already have our peak. No need for extra boundary checks. That gave me a second shorter solution. Also broke my second assumption > binary search doesn't always need while(low <= high). Sometimes while(low < high) is cleaner. Two wrong assumptions fixed in one problem 🙌 Took help but questioned it, understood it, then coded it myself. Github Repo link : https://lnkd.in/grF5ACw5 **Any other wrong assumption you had about binary search? Drop it below 👇** #DSA #Java #LeetCode #BinarySearch #LearningInPublic
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