📊 LeetCode Challenge: Median of Two Sorted Arrays Today’s problem was one of the most elegant and widely discussed challenges in algorithmic problem solving — finding the median of two sorted arrays. 💡 Problem Summary You’re given two sorted arrays, nums1 and nums2, and you need to find the median of the combined sorted array. The catch? You must do it in O(log(m + n)) time — meaning, no simple merging allowed 🚫 🧠 The Intuition At its heart, this is a binary search problem disguised as a math puzzle. The trick is to find a partition between the two arrays such that: Every element on the left side of the partition is less than or equal to every element on the right side. Once that partition is found — the median lies either in the middle element(s) of these partitions. 🧩 Why It’s Interesting It transforms a two-array problem into a search problem on one array. It’s a brilliant example of reducing complexity through symmetry. And it highlights how binary search can be used far beyond just finding numbers. ⏱️ Complexity Time: O(log(min(m, n))) Space: O(1) 🌱 Key Takeaway This problem reminded me that powerful solutions often come from rethinking the approach, not just optimizing the code. Sometimes, stepping back and seeing the symmetry in a problem can simplify everything. #LeetCode #DSA #ProblemSolving #BinarySearch #Algorithms #CodingChallenge #Learning
Finding Median of Two Sorted Arrays in O(log(m + n)) Time
More Relevant Posts
-
Solving the Rotated Challenge: Search in Rotated Sorted Array (LeetCode 33)! 🚀 You know Binary Search is O(\log N), but what happens when the array is sorted and rotated? The standard two-pointer approach breaks down! The key insight is to realize that even though the whole array is rotated, at least one half of the array must be perfectly sorted. We exploit this property in every iteration. The Modified O(\log N) Approach: Find the midpoint, \text{mid}. Identify the Sorted Half: Check if \text{nums}[\text{left}] \le \text{nums}[\text{mid}]. If true, the left half is sorted. Otherwise, the right half is sorted. Target Check: If the \text{target} falls within the boundaries of the sorted half, we discard the other half. If the \text{target} is not in the sorted half, it must be in the unsorted half, so we discard the sorted half. This technique ensures we always cut the search space in half, maintaining the optimal O(\log N) time complexity. Always a satisfying problem to solve! #Algorithms #BinarySearch #CodingChallenge #LeetCode #TechSkills
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 91 Problem: K-th Permutation Sequence 🔢✨ This problem was a brilliant deep dive into mathematical reasoning and combinatorial logic, showing how understanding factorial patterns can help us find the k-th permutation without generating all permutations. 🧠 Problem Summary: Given n and k, we must return the k-th permutation sequence of numbers [1, 2, 3, …, n]. Instead of generating all n! permutations, the challenge is to find it directly and efficiently. ⚙️ My Approach: 1️⃣ Compute (n - 1)! to understand how many permutations start with each digit. 2️⃣ Use integer division (k // fact) to determine which digit should occupy the current position. 3️⃣ Update k to represent the position within the smaller block using k = k % fact. 4️⃣ Repeat the process while updating factorial and removing used digits. This way, each step mathematically determines the next digit of the permutation — no brute force, no recursion. 📈 Complexity: Time: O(n²) → Due to list operations and factorial adjustments. Space: O(n) → For storing the available digits. ✨ Key Takeaway: You don’t always need to generate all possibilities — sometimes, understanding the mathematical structure behind permutations can lead straight to the answer. 💡 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #Mathematics #FactorialLogic #Permutation #Combinatorics #Algorithms #Python #Optimization #EfficientCode #InterviewPrep #TechCommunity #LearningByBuilding #CodeEveryday
To view or add a comment, sign in
-
-
Day 14 of DSA Practice - Matrix & Math Utility Edition After diving into subarrays and matrix rotations earlier, I focused today on foundational math and matrix-based problems, the kind that sharpen your logic and help you think in patterns Here’s what I explored 1️⃣ Matrix Sum of Diagonals / Transpose of Matrix → For diagonal sum, iterated once while tracking both primary and secondary diagonals. → For transpose, swapped matrix[i][j] with matrix[j][i] across the main diagonal. 💡 Trick: Always start loops till n/2 or i < j to avoid redundant swaps in transposition! 2️⃣ Find Element with Maximum Frequency → Used a HashMap to store frequency counts and extracted the key with the highest value. 💡 Trick: Simple frequency map logic yet it strengthens counting-based reasoning for array problems. 3️⃣ Count Pairs with Even Sum / Odd Sum → Counted even and odd elements separately. → Used combinations: Even + Even → Even Odd + Odd → Even Even + Odd → Odd 💡 Trick: Reduced O(n²) pair iteration to O(1) with counting logic! 4️⃣ Check Leap Year / Day of Week Computation → Used leap year condition: (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) 💡 Trick: Zeller’s Congruence (or calendar logic) for weekday computation, a fun blend of math + logic 5️⃣ Decimal → Binary / Binary → Decimal Conversion → For decimal to binary: continuously divided by 2 and reversed the remainder string. → For binary to decimal: processed digits from right to left with powers of 2. 💡 Trick: Great refresher for bit manipulation concepts, essential for upcoming DSA rounds ✨ Takeaway: Math and matrix-based problems may look simple but they’re the foundation of algorithmic thinking. Every clean logic here adds another layer to precision, pattern recognition, and analytical flow #DSA #Matrix #ProblemSolving #Java #LogicBuilding #LearningEveryday #WomenInTech #CodingJourney #MathInCode
To view or add a comment, sign in
-
📊 The Ultimate Algorithms Roadmap for Developers 📊 Excited to share this comprehensive algorithms roadmap that I've found incredibly valuable in my technical journey! This visual guide by @debugwithshubham breaks down the essential algorithms every developer should know: 🔍 Searching: From simple linear search to complex interpolation search techniques 🔄 Sorting: Eight powerful methods to organize data efficiently 🌐 Graph Algorithms: Master network problems with Dijkstra's, Bellman-Ford, and other critical pathfinding approaches 📱 Array & String: Kadane's algorithm, pattern matching, and dynamic programming fundamentals 🧩 Basics & Others: Compression techniques and essential algorithms like A* Search Whether you're preparing for technical interviews or looking to strengthen your algorithmic thinking, this roadmap serves as an excellent reference point! What algorithm category do you find most challenging? Let's discuss in the comments! 👇 If you want to stay updated with more such amazing and exclusive opportunities follow for more Shubham Maurya #ProgrammingFundamentals #AlgorithmsAndDataStructures #TechLearning #DeveloperResources #CodingJourney
To view or add a comment, sign in
-
-
This weekend, I built a small technical project for fun: a lightweight local vector engine (shards, HNSW indexing, fallback search, modular embedder, API server, logs…). Nothing commercial. Just something I decided to open-source for the community. Not perfect, not “enterprise-grade”. Just clean, simple, functional code — the kind of tool I couldn’t find anywhere in a minimal form. If it helps someone in their experiments (RAG, LLMs, embeddings, research…), good. If not, that’s fine too. Here is the open-source release: 🔗 https://lnkd.in/guK-Qknz Use it, break it, learn from it, improve it. Sharing what I build is my way to give back. #Python #AI #LLM #OpenSource #MachineLearning #Developer #RAG
To view or add a comment, sign in
-
-
🔹 Day 65 of #100DaysOfLeetCodeChallenge 🔹 Problem: Generate Parentheses Focus: Recursion + Backtracking 💡 The Challenge: Generate all valid combinations of n pairs of parentheses. Sounds simple? The trick is ensuring every string remains valid throughout construction! 🧠 My Approach: Used backtracking to build strings intelligently: Add '(' when we haven't used all n opening brackets Add ')' only when it won't break validity (close < open) Base case: Both counts reach n → valid combination found! ✅ 📊 Complexity Analysis: ⏳ Time: O(2ⁿ) — exploring possible combinations 💾 Space: O(n) — recursion stack depth 📌 Example: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] 🎯 Key Takeaway: Backtracking shines when you need to explore all possibilities while intelligently pruning invalid paths. This problem perfectly illustrates the power of constraint-based recursion! What's your favorite backtracking problem? Drop it in the comments! 👇 Day 65/100 complete. Onwards to mastering DSA, one problem at a time! 💪 #LeetCode #Algorithms #DataStructures #BacktrackingAlgorithms #TechCareers #SoftwareEngineering #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
#Day25 of My #100DaysCodingChallenge 🚀Today’s focus was on string processing and logical evaluation — tackling problems that strengthen both algorithmic thinking and text manipulation. 🔹 Problem 1: Valid Palindrome Approach: First, I removed all non-alphanumeric characters using regex and converted the string to lowercase. Then, I used a two-pointer approach (one from start, one from end) to check if the cleaned string reads the same backward and forward. ⏳ Time Complexity: O(n) 📦 Space Complexity: O(n) (due to the cleaned string) 🔹 Problem 2: Compare Vowels and Consonants (C++) Approach: Iterated through each character, counting vowels and consonants using a predefined set of vowel characters. Compared counts to print: “Yes” → if vowels > consonants “No” → if consonants > vowels “Same” → if counts are equal ⏳ Time Complexity: O(n) 📦 Space Complexity: O(1) ✨ Takeaway: String-based problems refine attention to detail, pattern recognition, and efficient pointer usage — foundational for text analytics and parsing systems. Grateful to Abhishek Kumar Sir and K.R. Mangalam University for their continued mentorship 🙌. #100DaysOfCode #DSA #ProblemSolving #StringManipulation #LeetCode #CodingChallenge #KRmangalamUniversity #Algorithms #DataStructures
To view or add a comment, sign in
-
-
🚀 Day 6 of #100DaysOfLeetCode: Two Sum Continuing strong with Day 6 of my "DSA with edSlash – 100 Days of LeetCode" journey! Today's problem is a classic that appears in countless technical interviews and lays the foundation for more complex algorithmic challenges. ✅ Problem Solved: Two Sum Task: Given an array of integers and a target value, find the indices of two numbers that add up to the target. 💡 Key Insight: This problem elegantly demonstrates the power of hash maps for efficient lookups: Brute Force Approach: Checking all pairs would take O(n²) time Optimal Solution: Using a hash map to store numbers and their indices allows us to find complements in O(1) time, reducing overall complexity to O(n) Core Strategy: For each number, calculate its complement (target - current number) and check if we've seen it before 🔍 Learning Highlight: Today reinforced why understanding time-space tradeoffs is crucial in algorithm design. The hash map approach transforms an O(n²) solution into an elegant O(n) one by sacrificing some space for dramatic time improvement. This pattern of trading space for time is fundamental to solving many array and searching problems efficiently. The Two Sum problem is more than just a coding challenge - it's a blueprint for solving countless other problems involving pairs, complements, and efficient searching! #LeetCode #HashTable #Algorithms #DataStructures #ProblemSolving #SoftwareEngineering #CodingInterview #TwoSum #Edslash #100DaysOfCode #ComputerScience
To view or add a comment, sign in
-
-
🚀 Day 8 of #100DaysOfLeetCode: Maximum Product of Two Elements in an Array Continuing my journey with "DSA with edSlash – 100 Days of LeetCode"! Today's problem presented a clever optimization challenge that combined mathematical reasoning with efficient array processing. ✅ Problem Solved: Maximum Product of Two Elements in an Array Task: Find the maximum value of (nums[i]-1) * (nums[j]-1) for two different indices i and j. 💡 Key Insight: This problem has a beautifully simple mathematical solution: Fundamental Insight: The maximum product will always come from the two largest numbers in the array (after subtracting 1 from each) Efficient Strategy: Instead of checking all possible pairs (O(n²) time), we can find the two largest numbers in a single pass through the array Optimal Approach: Track the largest and second-largest elements while iterating, achieving O(n) time complexity 🔍 Learning Highlight: Today reinforced how mathematical intuition can dramatically simplify algorithmic challenges. What initially appears as a combinatorial problem requiring checking all pairs reduces to a straightforward search for extreme values. This pattern of leveraging mathematical properties to optimize solutions is incredibly powerful and appears frequently in technical interviews. The problem also emphasized the importance of analyzing problem constraints before coding - sometimes the most efficient solution comes from understanding the underlying mathematical structure rather than applying brute force! #LeetCode #Arrays #Optimization #Algorithms #ProblemSolving #SoftwareEngineering #DataStructures #Math #Edslash #100DaysOfCode #ComputerScience
To view or add a comment, sign in
-
-
🚀 Solving "Set Matrix Zeroes" — A Clean Way to Think About It Today I tackled one of those deceptively simple but conceptually deep problems on LeetCode: Set Matrix Zeroes (Problem #73). 🧩 The Challenge: Given an m x n matrix, if any element is 0, set its entire row and column to 0 — and do it in place (no extra matrix allowed). At first, it sounds easy... until you realize that updating zeros immediately can cause a chain reaction of incorrect updates. 🧠 My Approach: I explored two different strategies 👇 1️⃣ Using Extra Space (Intuitive) Scan the matrix, record which rows and columns contain zeroes. In a second pass, set those rows and columns to zero. ✅ Easy to understand ⚠️ Space complexity = O(m + n) 2️⃣ Optimized In-place (Constant Space) Use the first row and first column as markers. When a zero is found, mark its row and column by setting the first cell in that row and column to 0. In a second pass, use those markers to update the matrix. ✅ Time = O(m × n) ✅ Space = O(1) 💡 What I Learned The key to in-place matrix problems is preserving state while updating. Using the matrix itself as a storage structure can reduce space without losing clarity. Sometimes the hard part isn’t coding — it’s finding a way to avoid overwriting useful information. 🧩 Pattern Recognized: “In-place grid modification using marker rows and columns.” This pattern also appears in problems like Game of Life, Rotate Image, and Flood Fill. 💬 Question for my network: What’s your favorite trick for solving in-place matrix problems efficiently? #LeetCode #Python #DataStructures #Algorithms #CodingChallenge #ProblemSolving #CSstudent #TechJourney #TwoPointers #MatrixManipulation
To view or add a comment, sign in
-