Day 13 of 30-day Coding Sprint Today's challenge was a perfect lesson in why complexity analysis matters. When the input reaches 10^15, O(n) isn't just slow, it's impossible. 1922. Count Good Numbers - The Logic: Even indices (0, 2, 4 ...) must be even digits (0, 2, 4, 6, 8) → 5 possibilities. - Odd indices (1, 3, 5 ...) must be prime digits (2, 3, 5, 7) → 4 possibilities. Total "Good" numbers = 5^even _indices * 4^odd_indices. The Bottleneck: With n up to 10^15, a simple loop to calculate power will result in a Time Limit Exceeded (TLE) error. We need to jump from O(n) to O(log n). - The Optimal Strategy: Binary Exponentiation + BigInt - Binary Exponentiation: By halving the power at each step, x^n = (x^n/2)^2, we calculate the result in logarithmic time. BigInt & Modulo: Handling numbers this large in JavaScript requires BigInt to prevent precision loss and consistent % mod operations to avoid overflow. Note: In the world of Big Data and 10^15 constraints, math is your best optimization tool. Transitioning from O(n) to O(log n) is the difference between a program that runs for days and one that finishes in milliseconds. #30DaysOfCode #DSASprint #LeetCode #JavaScript #BigInt #Recursion #Math #Complexity
Optimizing Complexity Analysis with BigInt and Binary Exponentiation
More Relevant Posts
-
🚀 Day 61 | LeetCode Medium 📄 Print Words Vertically Today’s problem was a really nice mix of string manipulation + indexing logic. Simple idea, but requires careful handling of spaces and boundaries. 🧠 Problem Intuition We’re given a sentence, and instead of printing words horizontally, we need to: 👉 Print them column by column, i.e., vertically. Key observations: Words can have different lengths Missing characters should be treated as spaces Trailing spaces must be trimmed 🔍 Key Strategy Split the sentence into words Find the maximum word length For each index x from 0 → maxLength-1: Traverse all words Append character if exists, else append space Remove trailing spaces before adding to result ✨ Why this works Direct character access avoids extra transformations Handles uneven word lengths gracefully Clean loop structure → easy to reason about Time Complexity: O(n × maxWordLength) Space Complexity: O(n) ✅ Key Learning String problems often become easy when you: Think in terms of indices Control formatting (like spaces) carefully This pattern shows up a lot in: Text formatting Matrix-like string problems 📌 Final Thought Not every medium problem needs fancy algorithms — sometimes clean iteration + edge handling is the real challenge. On to Day 62 💪 🔗 GitHub Solution: 👉 https://lnkd.in/gTeSSjs8 #LeetCode #LeetCodeDaily #Day61 #StringManipulation #Java #DSA #ProblemSolving #MediumProblems #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day-7 — Container With Most Water (Two Pointer Pattern) 💻 Platform: LeetCode (#11) Before jumping into today’s problem, a quick note from yesterday: That problem strengthened my understanding of prefix–suffix contribution and space optimization. Coming to today’s challenge: Given an array of heights, choose two lines that hold the maximum water. The key formula: Area = min(height[left], height[right]) × width Instead of checking every pair (O(n²)), I used the Two Pointer technique: • Start with the widest container (left at 0, right at n-1) • Compute area • Move the pointer pointing to the smaller height • Continue shrinking the search space The most important realization: The shorter boundary limits the water level. Moving the taller boundary only reduces width without improving height — so it cannot produce a better result. 🔍 Key takeaways: ✔ Two Pointers is about eliminating impossible improvements ✔ Greedy pointer movement can lead to optimal solutions ✔ Starting from extremes can simplify search problems Learning to recognize patterns is making problem-solving feel less random each day. Solutions are available here: 🔗https://lnkd.in/gW8atfqw Day-7 complete. More tomorrow 🚀 #30DaysOfCode #LeetCode #DSA #Java #Algorithms #ProblemSolving #SoftwareEngineering #Developers
To view or add a comment, sign in
-
-
🚀 24/02/26 — From Rotations to Root Nodes: Today’s DSA Wins Today I tackled some clever problems that pushed me to think differently about strings and trees. Here’s a quick breakdown of what I learned and implemented: 🔄 Strobogrammatic Numbers — LeetCode 246 A number that looks the same when rotated 180° (like "69" or "88"). Approach: Used a Two-Pointer technique with a rotation map including '0', '1', '8', '6', and '9'. Complexity: O(N) Time and O(1) Space. Result: 100% runtime beats (0ms). 🧵 Append Characters to Make Subsequence — LeetCode 2486 Goal: Find the minimum characters to append so that string t becomes a subsequence of string s. Approach: Applied a Greedy Two-Pointer strategy to match characters while traversing both strings. Complexity: O(N + M) Time and O(1) Space. 🌳 LCA of Binary Tree III — LeetCode 1650 Nodes have parent pointers, which made this problem fascinating. I implemented two approaches: Approach 1 — HashSet Ancestor Tracking: Store all ancestors of node p in a HashSet, then check node q’s ancestors against it. Efficiency: O(N) Time , O(N) Space. 🚀 Approach 2 — Linked List Intersection Trick: Treat paths to the root as two intersecting linked lists. Redirect pointers when reaching null so they meet at the Lowest Common Ancestor. Efficiency: O(N) Time , O(1) Space. 💡 Lightbulb Moment Realizing that the Intersection of Two Linked Lists pattern works perfectly for trees with parent pointers was a game-changer. Today was proof that pattern mastery > memorizing problems. Thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the guidance and high-quality resources that keep me learning. Visual notes + 100% runtime screenshots attached below! 📄👇 #DSA #Java #LeetCode #CodingJourney #TwoPointers #BinaryTree #Optimization #LearningInPublic #CTOBhaiya
To view or add a comment, sign in
-
Day 5 of 150: Building Scalable Systems with Pythonic Architecture As codebases grow, functional code is not enough—it must be maintainable. Today’s deep dive into Functions and Modular Programming focused on the transition from writing scripts to building scalable systems. Technical Focus Areas: • Architectural Efficiency: Using functions to eliminate redundancy and decompose complex tasks into manageable, testable units. • The Scope Hierarchy: Mastering the nuances of global vs. nonlocal scopes to prevent side effects and ensure memory efficiency. • Functional Programming: Exploring Lambdas and the distinction between Pure vs. Impure functions to achieve predictable code behavior. • Modularization: Leveraging Python Imports and init files to organize code into professional-grade packages. • Advanced Parameter Handling: Implementing flexible argument handling and multiple return patterns for dynamic logic. Real-World Application: Applied these principles to build a Loyalty Points Tracker and an Order Invoice Generator, focusing on documentation and PEP-compliant built-ins. Scaling logic requires discipline and structure. One day at a time. #Python #SoftwareEngineering #CleanCode #SystemDesign #150DaysOfCode #InterviewPrep
To view or add a comment, sign in
-
🚀 300+ LeetCode Problems Solved I’ve crossed 300+ problems on LeetCode, and this phase of preparation has been less about numbers and more about depth, patterns, and optimization. 🧠 Primary focus areas 🟣 Dynamic Programming State design and transitions ➜ Memoization ➜ Tabulation ➜ Space optimization. Worked on classic patterns like 0/1 Knapsack, LIS, and DP on grids & strings. 🔵 Graphs Built strong fundamentals using BFS and DFS, explored connected components, cycle detection, and topological sorting, and developed solid intuition for shortest path problems using Dijkstra and BFS-based approaches. 🟢 Strings Practiced sliding window and two-pointer techniques, hashing and frequency-based optimizations, and problems combining greedy logic with DP on strings. ⚙️ What improved during this journey 🔁 Brute-force ideas evolved into optimized solutions. 📈 Solutions now include clear time and space complexity analysis. 🧩 Shifted from solving problems individually to recognizing recurring patterns. 🛠️ Became more confident handling edge cases under tight constraints. 💡 Key takeaway 👉 Strong solutions come from understanding constraints, identifying patterns, and optimizing step by step before writing code. 🎯 Continuing to iterate and refine — Consistency + Curiosity = Growth 🚀 #LeetCode #DSA #Algorithms #DynamicProgramming #Graphs #Strings #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 300 of solving 365 medium questions on LeetCode!🎉 Milestone Reached! 300 days of consistency. Only 65 to go! 🔥 Today’s challenge: “2134. Minimum Swaps to Group All 1's Together II” ✅ Problem: Given a binary circular array (where the last element connects to the first), find the minimum number of swaps needed to group all the 1s into a single contiguous block. ✅ Approach (Sliding Window — Optimized) This sounds like a complex swapping simulation, but it's actually a fixed-size window problem. Determine Window Size: Count the total number of ones in the array (total_ones). This is the size of our target block. The Goal: We want to find a subarray of length total_ones that already contains the maximum number of 1s. Why? If a window has X ones, it has total_ones - X zeros. Those zeros are exactly the positions we need to swap! Minimizing the zeros in the window minimizes the swaps. Circular Trick: To handle the "circular" property without complex index math, we can conceptually simulate the window sliding past the end of the array and wrapping around to the start (or just append nums to nums). ✅ Key Insight Don't simulate the swaps! Reframe the problem: "Where can I place a window of size K such that it covers the most existing 1s?" The "holes" (zeros) in that best window represent the minimum work required. ✅ Complexity Time: O(N) — We count the ones, then slide the window across the array once. Space: O(1) — No extra arrays needed if we handle indices carefully. 🔍 Check out my Python solution in the attached image! 🔥 Flexing my coding skills until recruiters notice! #LeetCode365 #SlidingWindow #Arrays #Python #ProblemSolving #DSA #Coding #SoftwareEngineering #Milestone
To view or add a comment, sign in
-
-
Day 9 of 150: Advanced Class Relationships — Inheritance, Composition, and MRO Building on the foundations of OOP, today’s session focused on how objects interact and share behavior. Understanding the trade-offs between Inheritance and Composition is a high-frequency topic in system design interviews. Technical Focus Areas: • Inheritance vs. Composition: Evaluating "Is-A" vs. "Has-A" relationships to build flexible and maintainable class hierarchies. • Base Class Access: Mastering the three ways to interface with parent classes, including the use of super() for clean, maintainable code. • Method Resolution Order (MRO): A deep dive into the C3 Linearization algorithm that Python uses to navigate multiple inheritance and prevent the "Diamond Problem." • Method Overriding: Implementing specialized behavior in child classes while preserving the integrity of the base class. • Real-World Application: Developed a Smart Home Device Tracker to implement complex device hierarchies and shared attributes across varying hardware types. Mastering how classes relate to one another is key to building modular, enterprise-grade software. 141 days to go. #Python #SoftwareEngineering #OOP #SystemDesign #150DaysOfCode #InterviewPrep
To view or add a comment, sign in
-
🚀 LeetCode 110 – Balanced Binary Tree Today I solved LeetCode #110 – Balanced Binary Tree. 📌 Problem Statement Given a binary tree, determine whether it is height-balanced. A binary tree is considered height-balanced if: For every node, the height difference between its left and right subtree is not more than 1. 🧠 Approach & Technique Used To solve this problem efficiently, I used the Depth-First Search (DFS) approach with a bottom-up recursion strategy. 🔎 Key Idea: Instead of checking height separately for every node (which would increase time complexity), We calculate height while simultaneously verifying balance. If at any node the height difference is greater than 1, we return -1 immediately. This avoids unnecessary recalculations. ⚡ Time & Space Complexity Time Complexity: O(n) → Each node is visited once. Space Complexity: O(h) → Recursive stack space (h = height of tree). 💻 Optimized Python Code class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: def checkHeight(node): if not node: return 0 left = checkHeight(node.left) if left == -1: return -1 right = checkHeight(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 return 1 + max(left, right) return checkHeight(root) != -1 🎯 Why This Approach Is Better? ✅ Avoids repeated height calculations ✅ Stops early when imbalance is detected ✅ Clean and optimized recursion ✅ Industry-level approach for tree problems Consistently solving tree problems is strengthening my understanding of recursion and DFS patterns. Looking forward to solving more problems and sharing my journey 🚀 🔥 Hashtags for Better Reach #LeetCode #CodingInterview #DSA #BinaryTree #Recursion #PythonDeveloper #SoftwareEngineer #ProblemSolving #TechCareer #CodingJourney #100DaysOfCode #DataStructures #Algorithms #InterviewPreparation
To view or add a comment, sign in
-
-
Day 191: Advanced Stacks and Monotonic Patterns I am on Day 191 of my coding journey. Today I focused on using Stacks to solve math problems and search for patterns in arrays. I revisited the Min Stack problem to make it faster. By storing the current minimum value along with each number in the stack, I can now find the smallest number in O(1) time. This means I do not have to look through the whole stack to find the minimum. Next, I solved the problem of removing outermost parentheses. I tried two ways to do this. First, I used a stack to track the depth. Then, I realized I could just use a simple counter variable to track the level. If the level is higher than one, I keep the bracket. This logic makes the code much smaller and faster. I also worked on Reverse Polish Notation. This is a way of writing math problems where the operators come after the numbers. A stack is the perfect tool for this. I push numbers onto the stack and whenever I see a symbol like plus or minus, I pop the top two numbers, solve them, and push the result back. Finally, I learned about the Next Greater Element. This is a very important pattern. I used a Monotonic Stack to keep track of numbers as I moved backward through the array. This allows me to find the next bigger number for every element without using a slow nested loop. Today taught me that stacks are not just for storing data. They are great for solving math and finding relationships between numbers in a list. #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #CodingJourney #ProgrammingLogic #DataStructures #Algorithms #WebDevelopment #SoftwareEngineering #CodeNewbie #TechSkills #JavaScriptDeveloper #ProblemSolving #MonotonicStack #LogicBuilding #DailyCodingChallenge #ComputerScience #BackendDevelopment #FrontendDevelopment
To view or add a comment, sign in
-
Day 17 – Implementing the Singleton Pattern in a Ride Booking System: Today, I implemented the Singleton Design Pattern from scratch in Python and applied it to a complete Ride Booking System. Understanding a design pattern conceptually is one thing, but implementing it in a real system makes the learning much deeper. What I Learned About Singleton The Singleton Pattern ensures that only one instance of a class exists throughout the application lifecycle and provides a global access point to it. In Python, this can be implemented by overriding the __new__ method: • A static class-level variable holds the instance • If no instance exists, it is created • If an instance already exists, the same object is returned • Every reference points to the same memory object When I created two objects: system1 = RideBookingSystem() system2 = RideBookingSystem() Both variables pointed to the same instance. The expression system1 is system2 returned True, confirming the Singleton behavior. Applying Singleton in a Full Ride Booking System I extended this implementation to my complete ride system architecture. The RideBookingSystem was designed as a Singleton because: • There should be only one central booking manager • All ride operations must update the same active rides collection • Ride IDs must be generated consistently • Shared state must remain synchronized across the application By making it Singleton: • No duplicate booking managers are created • Active ride tracking remains consistent • System-wide coordination becomes easier • Resource usage is controlled Design Insight Singleton is useful when: • Managing shared resources • Coordinating system-wide state • Implementing logging systems • Handling configuration managers • Creating centralized controllers However, it should be used carefully to avoid tight coupling and testing difficulties. LLD Takeaway: Day 17 reinforced an important principle: Design patterns are powerful only when applied in the right context. Implementing Singleton in a real ride booking architecture helped me understand how object lifecycle management impacts system consistency and scalability. Continuing to strengthen my Low Level Design foundations by applying patterns to practical systems. #LLD #LowLevelDesign #DesignPatterns #SingletonPattern #SystemDesign #OOP #SoftwareDevelopment #BackendDevelopment #LearningJourney
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