✳️Day 40 of #100DaysOfCode✳️ 🚀 Cracking the Code: Solving "Ugly Number III" with Math & Binary Search 1️⃣ The Power of Binary Search Instead of counting up from 1, we treat the answer as a range. By using Binary Search on the search space (up to 2 \times 10^9), we can efficiently narrow down the n^{th} number. We check a candidate middle value to see if there are at least n ugly numbers below it. 2️⃣ Inclusion-Exclusion Principle (The Math Secret) To count how many numbers up to M are divisible by a, b, or c, we can't just add them up—that would double-count the multiples they share. I used the Inclusion-Exclusion Principle to get an accurate count: Add counts of numbers divisible by a, b, and c individually. Subtract the counts of numbers divisible by their pairs: lcm(a, b), lcm(b, c), and lcm(a, c). Add back the count of numbers divisible by all three: lcm(a, b, c). 3️⃣ Least Common Multiple (LCM) & GCD To find the LCM accurately, I implemented a helper function using the Greatest Common Divisor (GCD). This ensures that we correctly identify the overlapping multiples without overflow issues. Key Takeaway: Sometimes the most efficient way to "search" isn't to look at every item, but to use mathematical properties to "jump" to the right answer. #LeetCode #Java #Algorithms #CompetitiveProgramming #SoftwareEngineering #BinarySearch #MathInCode
Solving Ugly Number III with Binary Search and Math
More Relevant Posts
-
The High Cost of the Wrong Initial Choice I have seen complex computation logic for over a million records take hours to run simply because of inefficient, row-by-row processing that is offered by database stored procedures and traditional java/python code. It is slow, impossible to scale, and eventually kills your product's edge in the market. By moving to vectorized logic with tools like NumPy or Polars, you can turn those hours of computation into milliseconds. This is not just about using newer tools, it is about leveraging modern execution like #SIMD (Single Instruction Multiple Data) and #multithreading to gain a massive competitive advantage. If your backend is computation heavy and you're still stuck in legacy loops, you are leaving performance, market edge and money on the table. References: https://lnkd.in/g8j3A5Bn https://lnkd.in/gaPnFUQm https://lnkd.in/gWt9WHnp #DataEngineering #SystemDesign #NumPy #PerformanceOptimization #Scalability #PythonProgramming #TechStrategy #Vectorization #TechToolChoice
To view or add a comment, sign in
-
✳️Day 39 of #100DaysOfCode✳️ Kth Smallest Element in a Sorted Matrix Here’s the step-by-step logic I followed to solve this efficiently: 1️⃣ Defining the Search Space Since the rows and columns are already sorted, we know the smallest element is at matrix[0][0] and the largest is at matrix[n-1][n-1]. Instead of searching through indices, I performed a Binary Search on the range of values between the low and high elements. 2️⃣ The "Count" Helper Function The core of this approach is a helper function that counts how many elements in the matrix are less than or equal to a specific mid value. In my current implementation, I used a nested loop approach. Optimization Tip: Since the matrix is sorted row-wise and column-wise, this count can actually be optimized to O(n) by starting from the bottom-left and moving toward the top-right! 3️⃣ Narrowing the Range Based on the count returned: If the number of elements \le mid is less than k, it means our target k^{th} element must be larger. So, I adjusted the low pointer to mid + 1. Otherwise, the target could be mid itself or something smaller, so I updated the high pointer and stored the potential answer. 4️⃣ Complexity Check By using Binary Search on the value range, we achieve a much better memory complexity than O(n^2), satisfying the problem's constraints and keeping the solution performant. Key Takeaway: Binary Search isn't just for sorted arrays; it’s a powerful tool for searching through any monotonic search space! #LeetCode #Java #DataStructures #Algorithms #CodingInterview #ContinuousLearning #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Solved LeetCode Problem #69 – Sqrt(x) Today I worked on a classic problem that beautifully demonstrates how Binary Search can be applied beyond arrays. 🔍 Problem Insight: Given a non-negative integer x, the goal is to compute the integer square root (i.e., the floor value of √x) without using built-in functions. 💡 Approach Used: I applied Binary Search on the answer space: Defined a search range from 1 to x Checked whether mid * mid is less than, equal to, or greater than x Narrowed down the range accordingly Tracked the best possible answer when an exact square wasn’t found 🧠 Key Learning: Binary search isn’t just for searching—it can be used to optimize mathematical problems Handling integer overflow (using long) is crucial Understanding how to compute floor values in algorithmic problems 📈 Complexity: Time: O(log x) Space: O(1) ✨ This problem strengthened my understanding of: Binary Search on range/answer Efficient problem-solving techniques Writing optimized and scalable code Consistently solving such problems is helping me build strong fundamentals in DSA and problem-solving 💪 #LeetCode #DSA #BinarySearch #Algorithms #Coding #ProblemSolving #Java #TechJourney
To view or add a comment, sign in
-
-
## 🧩 Solved LeetCode 9 – Palindrome Number Today I revisited a fundamental integer manipulation problem: determining if a number reads the same forward and backward without converting it to a string. 🔍 **Problem Insight:** While string conversion makes this trivial, the real challenge is solving it mathematically. The goal is to reverse the integer (or half of it) and compare it to the original while being mindful of potential integer overflow. 💡 **Key Learnings:** * **Negative Numbers:** Any negative number is immediately invalid (e.g., -121 becomes 121-). * **Mathematical Reversal:** Using modulo % 10 and integer division / 10 allows us to "pop" and "push" digits. * **Optimization:** We only need to reverse **half** of the number. Once the original number becomes less than or equal to the reversed half, we've reached the middle. * **Edge Case Savvy:** Numbers ending in 0 (except 0 itself) cannot be palindromes. ⚙️ **Approach Used:** 1. Eliminate negative numbers and numbers ending in 0. 2. Build the reversed half of the number by iteratively taking the last digit. 3. Stop when the reversed part is \ge the remaining part. 4. Check for equality (handling odd-lengthed numbers by dividing the reversed part by 10). 📊 **Complexity:** * **Time:** O(\log_{10}(n)) — we divide the input by 10 in every iteration. * **Space:** O(1) — constant space used regardless of input size. 🔥 **Takeaway:** This problem is a perfect example of why we shouldn't always reach for the easiest data type conversion. Thinking in terms of pure logic and math often leads to a more memory-efficient and elegant solution. #LeetCode #Algorithms #Math #ProblemSolving #CodingJourney #Java #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
Wow! That's maths. Impressive question. Had fun solving it. The problem asks for the minimum operations to make all elements in a 2D grid equal by adding or subtracting a given integer x. At first glance, you might think about finding the average of all the numbers. However, the mathematical trick to minimize absolute differences is actually to target the median. My Approach: Flatten & Sort: I converted the 2D grid into a 1D array and sorted it to easily find the median values. The Window Check: To be absolutely safe, my code checks a small window of elements right around the median (((m * n) / 2) - 2 to + 2). Modulo Validation: If the absolute difference between an element and the target isn't perfectly divisible by x (val % x != 0), it's mathematically impossible, so we break and return -1. Happy to get this one Accepted! #LeetCode #Java #Algorithms #ProblemSolving #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
#Day74 of my second #100DaysOfCode Binary search variations getting more interesting now. DSA • Solved Find Minimum in Rotated Sorted Array (LeetCode 153) – Brute: linear scan → O(n) – Optimal: binary search with an early check for already sorted part → O(log n) • Key idea: the minimum always lies in the unsorted portion, and if a part is already sorted, the answer can be taken directly • Difference from previous problems: instead of searching for a target, we’re tracking the minimum while narrowing the search space • Edge cases: – already sorted array – single element case – careful updates while narrowing the range This one was more about understanding the pattern than just applying binary search. #DSA #BinarySearch #LeetCode #Algorithms #Java #100DaysOfCode #WomenWhoCode #BuildInPublic #LearningInPublic
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 5/50 🔍 Problem: Missing Number Today’s problem was a great example of how mathematical optimization can simplify logic and improve efficiency. 💡 Approach: Instead of using extra space or sorting, I applied the Mathematical Formula method: Calculated the expected sum of numbers from 0 to n Found the actual sum of the given array The difference between them gives the missing number ⚡ This approach avoids unnecessary iterations and extra memory usage. 📊 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) 📚 Key Learning: Sometimes the most optimal solution is not complex—it’s about recognizing patterns and applying the right formula. This problem reinforced the importance of mathematical thinking in algorithms. Consistency continues… 💪 #LeetCode #Algorithms #DataStructures #ProblemSolving #CodingJourney #Java #100DaysOfCode #StudentDeveloper #Learning
To view or add a comment, sign in
-
-
📅 Date: April 25, 2026 Day 4 of my LeetCode Journey 🚀 ✅ Problem Solved: 9. Palindrome Number 🧠 Approach & Smart Solution: While it's easy to solve this by converting the integer to a string and reversing it, that takes extra memory! I opted for a highly optimized mathematical approach. I reversed the integer by peeling off its digits one by one using modulo and division, keeping the space complexity to an absolute minimum. • Pseudo-code: Handle edge cases: If the number is less than 0, it can't be a palindrome, so return false. Store the original number in a temporary variable for final comparison. Initialize a 'reverse' variable to 0. Loop while the number is greater than 0: Extract the last digit: digit = x % 10. Add it to the reversed number: reverse = (reverse * 10) + digit. Remove the last digit from the original number: x = x / 10. Finally, return true if the original number matches the reversed number. This math-based solution avoids expensive string conversions and runs instantly! ⏱️ Time Complexity: O(log₁₀(n)) (We only iterate through the digits of the number) 📦 Space Complexity: O(1) (Only using a few integer variables) 📊 Progress Update: • Streak: 3 Days 🔥 • Difficulty: Easy • Pattern: Math / Digit Extraction 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Choosing mathematical operations over string manipulations is a great way to optimize basic algorithms! 💡 #LeetCode #DSA #Math #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
#CodeEveryday — My DSA Journey | Day 14 🧩 Problem Solved: Search a 2D Matrix (LeetCode #74) 💭 What I Learned: Used binary search by treating the 2D matrix as a flattened sorted array. Key idea: 👉 Convert 1D index → 2D coordinates using: row = mid / number_of_columns col = mid % number_of_columns At each step: ✔️ Calculated row and column from mid ✔️ Compared matrix value with target ✔️ Adjusted search space accordingly This approach avoids nested loops and gives optimal performance. ⏱ Time Complexity: O(log (m × n)) 🧠 Space Complexity: O(1) ⚡ Key Takeaways: ✔️ 2D problems can often be reduced to 1D using indexing tricks ✔️ Binary search works whenever the data is globally sorted ✔️ Index mapping is a powerful technique in matrix problems 💻 Language Used: Java ☕ 📘 Concepts: Binary Search · Matrix · Index Mapping · Optimization #CodeEveryday #DSA #LeetCode #Java #BinarySearch #Matrix #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
Most coding problems look different… until you realize they are just graphs in disguise. That’s where Graphs come in. A graph represents relationships using nodes (vertices) and edges (connections). You’ll find them everywhere from Google Maps finding routes to social media suggesting connections. Understanding Graphs Graphs can take different forms depending on the problem: • Directed and Undirected (based on direction) • Weighted and Unweighted (based on cost or distance) • Cyclic and Acyclic (DAG) These variations help model real-world scenarios more accurately. How Graphs Are Stored There are two main ways: • Adjacency Matrix → fast lookup but uses more space • Adjacency List → space efficient and used in most systems Core Traversal Techniques 🔹 BFS (Breadth-First Search) Moves level by level and helps find shortest paths in unweighted graphs 🔹 DFS (Depth-First Search) Goes deep into nodes and is useful for cycle detection and backtracking Important Algorithms Once basics are clear, these are must-know: • Dijkstra → shortest path • Bellman-Ford → handles negative weights • Kruskal & Prim → minimum spanning tree • Topological Sort → ordering in DAG How to Approach Graphs Start with basics, master BFS and DFS, then move to problems like cycle detection and shortest paths. With practice, patterns become clear. Graphs are not just a topic, they help you think in terms of connections and dependencies. 💬 Comment what kind of notes or topic you want next, and I will cover it in detail👇. #DSA #Algorithms #Java #Coding #InterviewPrep
To view or add a comment, sign in
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