Day 8 of Daily DSA 🚀 Solved LeetCode 319: Bulb Switcher 💡 Initially, the brute-force idea was to simulate all rounds using loops — but that leads to O(n) time complexity. 🔍 Key Insight (Math wins here): A bulb ends up ON only if it is toggled an odd number of times. This happens only for perfect squares, because only perfect squares have an odd number of divisors. So instead of looping till n, we can directly count perfect squares using: return (int) Math.sqrt(n); Why Math.sqrt() over loop? ✅ Reduces time complexity from O(n) → O(1) ✅ Cleaner & more readable code ✅ Much faster for large inputs Complexity: • Time: O(1) • Space: O(1) LeetCode Stats: • Runtime: 0 ms (Beats 100%) • Memory: 42.25 MB This problem is a great reminder that sometimes math is the real optimization 🧠✨ #DSA #LeetCode #Java #MathOptimization #ProblemSolving #DailyCoding #Consistency
Optimize LeetCode 319 with Math.sqrt() for O(1) Time Complexity
More Relevant Posts
-
🚀 Day 12/30 – Mastering Binary Search Patterns Today’s problem required finding the position of a target value in a sorted array — or determining where it should be inserted if it doesn’t exist. Rather than scanning linearly, I implemented a Binary Search approach to maintain optimal performance. 💡 Approach Maintain two pointers: left and right Compute mid carefully to avoid overflow Compare the target with the middle element Narrow the search space accordingly If the element is not found, return the left pointer as the insertion index This pattern ensures: ⏱ O(log n) time complexity 📦 O(1) space complexity 📊 Performance ✅ All test cases passed ⚡ 0 ms runtime (100% performance) 💾 Strong memory efficiency 📚 Key Takeaway Binary Search is more than just finding elements — it’s about identifying boundaries and understanding how search space evolves. Recognizing insertion logic as a natural extension of search strengthens problem-solving intuition. Day 12 complete. The fundamentals are getting sharper every day. #Day12 #30DaysOfCode #LeetCode #Java #BinarySearch #Algorithms #ProblemSolving #SoftwareEngineering #CodingJourney #Consistency #TechGrowth
To view or add a comment, sign in
-
-
🚀 Day 13/30 – Tracking Patterns in Arrays Today’s problem focused on finding the maximum number of consecutive 1’s in a binary array. While the logic is straightforward, the key is identifying and tracking streaks efficiently without using extra space. 💡 Approach Traverse the array once Maintain a running counter for consecutive 1’s Reset the counter when a 0 is encountered Continuously track the maximum streak using Math.max() This ensures: ⏱ O(n) time complexity 📦 O(1) space complexity 📊 Performance ✅ All test cases passed ⚡ Efficient runtime 💾 Constant space usage 📚 Key Takeaway Problems like this reinforce an important idea: Many array questions are about recognizing patterns and maintaining state correctly during traversal. Even simple problems sharpen attention to iteration logic and edge handling. Day 13 complete. Consistency + clarity = steady improvement. #Day13 #30DaysOfCode #LeetCode #Java #Algorithms #ArrayProblems #ProblemSolving #SoftwareEngineering #CodingJourney #Consistency #TechGrowth
To view or add a comment, sign in
-
-
🔥 Day 331 – Daily DSA Challenge! 🔥 Problem: 🟦 Perfect Squares Given an integer n, return the least number of perfect square numbers that sum to n. Example: 12 = 4 + 4 + 4 → answer = 3 13 = 4 + 9 → answer = 2 💡 Key Insight — Classic DP (Unbounded Knapsack Style) We build the solution bottom-up. For each number i, try subtracting every possible perfect square j² ≤ i. Core recurrence: Where: j² is any perfect square ≤ i +1 represents using that square 🧠 Why This Works 🔹 Every number can be represented as sum of 1² repeated → worst case = i 🔹 We iteratively improve this by checking larger squares 🔹 This is similar to coin change problem Coins = perfect squares Target = n ⚡ Optimized Plan: ✅ Create dp[n+1] ✅ Initialize dp[i] = i (worst case: all 1’s) ✅ For each i: Try every square j² ≤ i Update minimum ✅ Return dp[n] ✅ Time Complexity: O(n √n) ✅ Space Complexity: O(n) 💬 Challenge for you: 1️⃣ Can this be solved using BFS instead of DP? 2️⃣ How does Lagrange’s Four Square Theorem relate to this problem? 3️⃣ Can we optimize by precomputing squares only once? #DSA #Day331 #LeetCode #DynamicProgramming #Math #PerfectSquares #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 13/100 — Recursive Deconstruction Today’s Challenge: LeetCode 761 - Special Binary String 🧩 Yesterday was about bits; today was about Structural Grammar. Special Binary Strings aren't just 1s and 0s; they are a language. The Realization: A special string is like a valid set of parentheses. 1 is ( and 0 is ). To find the "lexicographically largest" version, you have to break the string into its most basic components, sort them, and put them back together. My 0ms Optimization Strategy: 1. Mental Mapping: Treated the string as a nested structure. If 1...0 is a special string, I stripped the outer layer, solved the inside, and then re-wrapped it. 2. Greedy Reassembly: Used Collections.sort() with a reverse comparator. In binary, "larger" just means the 1s appear as early as possible. 3. Memory Management: Minimized object creation by identifying "split points" first before committing to substring allocations. Reflection: Sometimes the fastest way to solve a problem isn't to iterate forward, but to look at the problem as a recursive tree. Every "Special" chunk is a node that can be reordered to maximize the total value. 13 days down. The logic is getting deeper. 87 days to go. 🛠️ #Java #DSA #LeetCode #100DaysOfCode #Recursion #StringAlgorithms #SoftwareEngineer #CodingJourney #Optimization
To view or add a comment, sign in
-
-
🔥 Day 336 – Daily DSA Challenge! 🔥 Problem: 🎯 Combination Sum III Find all valid combinations of k numbers that sum up to n, such that: Only numbers 1 through 9 are used Each number is used at most once No duplicate combinations 💡 Key Insight — Controlled Backtracking This is a constrained combination problem with: Fixed size → k numbers Fixed sum → n Limited choices → 1 to 9 No repetition We explore combinations in increasing order to avoid duplicates. 🧠 Core Recursion Logic At every step: Choose a number i Reduce remaining sum Move start to i + 1 (avoid reuse) Mathematically, we search for: Where: 1 ≤ i1 < i2 < ... < ik ≤ 9 ⚡ Optimized Plan: ✅ Start from 1 ✅ If: cur.size() == k AND sum == 0 → valid combination ✅ If: cur.size() == k OR sum < 0 → prune ✅ Try numbers from start → 9 ✅ Backtrack properly ✅ Time Complexity: O(C(9, k)) (Bounded search space) ✅ Space Complexity: O(k) 💬 Challenge for you: 1️⃣ How can you add pruning to stop early when remaining numbers can't reach sum? 2️⃣ What if numbers were 1 to 20 instead of 1 to 9? 3️⃣ Can you solve this iteratively using bitmasking? #DSA #Day336 #LeetCode #Backtracking #Combinations #Recursion #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Today’s Problem of the Day was Trapping Rain Water — a classic but tricky problem that tests your understanding of two-pointer optimization. ✅ 1111 / 1111 test cases passed ✅ 1 / 1 attempt 🔥 4-day streak ⭐ 8/8 points Instead of using extra prefix/suffix arrays, I implemented the optimized O(n) time and O(1) space two-pointer approach. Key idea: At every index, trapped water depends on min(leftMax, rightMax) - height[i] The challenge isn’t writing code — it’s recognizing why the smaller boundary determines the water level. Problems like this reinforce: • Boundary thinking • Space optimization • Clean pointer movement logic Consistency > Motivation. On to Day 5. 💪 #GeeksforGeeks #ProblemOfTheDay #DataStructures #Algorithms #Java #CodingJourney #100DaysOfCode
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 40 / 100 – LeetCode Challenge Problem: Next Permutation (Medium) Today’s problem was about finding the next lexicographically greater permutation of a given integer array. 📌 Key Idea: Instead of generating all permutations, we efficiently transform the array to its next permutation using a smart approach. 🔹 Steps followed: 1. Traverse from the right to find the first element where nums[i] < nums[i+1]. 2.Find the next greater element to the right of nums[i]. 3. Swap these two elements. 4.Reverse the elements after index i to get the smallest possible order. 💡 If the array is in descending order, the next permutation becomes the ascending order. Time Complexity: O(n) Space Complexity: O(1) Concepts Practiced: Array manipulation Lexicographical ordering Two-pointer technique In-place operations Consistent progress towards mastering Data Structures & Algorithms 💪 #Day40 #100DaysOfCode #LeetCode #Java #DSA #CodingChallenge
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟱𝟳/𝟭𝟬𝟬 — 𝗪𝗵𝗲𝗻 𝗦𝘁𝗮𝗰𝗸𝘀 𝗚𝗲𝘁 𝗚𝗿𝗲𝗲𝗱𝘆 Yesterday: Valid Parentheses. Basic stack. Today: Remove Duplicate Letters. Stack + greedy + frequency tracking. Level up. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟯𝟭𝟲: Remove Duplicate Letters (Medium) 𝗧𝗵𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Remove duplicate letters so the result is: Smallest in lexicographical order (dictionary order) Contains each letter exactly once Example: "bcabc" → "abc" The trick? Knowing when to remove a character from the stack to make room for a better one. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Monotonic stack + greedy decisions. 👉 Track frequency: how many times each character appears ahead 👉 Track visited: have we already used this character? 👉 For each character, pop stack if: Stack top is larger (worse for lexicographical order) Stack top appears again later (we can use it then) 👉 Push current character and mark visited Time: O(n), Space: O(1) — only 26 letters max. 𝗪𝗵𝗮𝘁 𝗖𝗹𝗶𝗰𝗸𝗲𝗱: This combines three patterns: Monotonic stack (maintaining order) Greedy algorithm (making locally optimal choices) Frequency tracking (knowing what's ahead) Solving it wasn't about knowing one technique. It was about combining them. 𝗖𝗼𝗱𝗲: https://lnkd.in/gzw6ACFr 57 down. 43 to go. 𝗗𝗮𝘆 𝟱𝟳/𝟭𝟬𝟬 ✅ #100DaysOfCode #LeetCode #Stack #MonotonicStack #GreedyAlgorithm #DataStructures #Algorithms #CodingInterview #Programming #Java #MediumLevel #PatternCombination
To view or add a comment, sign in
-
🚀 Day 11/30 – LeetCode 21: Merge Two Sorted Lists Today’s problem was about merging two sorted linked lists into one sorted list. Since both lists are already sorted, the key idea is simple: 👉 Always attach the smaller node first. 💡 Approach (Iterative + Dummy Node) Instead of recursion, I used: ✅ A dummy node to simplify edge cases ✅ A pointer (curr) to build the merged list ✅ A while loop to compare values ✅ Attach the remaining list at the end This avoids extra recursion space and keeps it clean. 🧠 Code Logic Create a dummy node. Compare list1.val and list2.val. Attach the smaller one to curr.next. Move the pointer forward. After loop, attach remaining nodes. ⏱ Complexity Time Complexity: O(n + m) Space Complexity: O(1) (No recursion stack used) 🎯 Key Learning ✔ Dummy nodes simplify linked list problems ✔ Iterative approach improves space efficiency ✔ Always think about leftover nodes after loop 📊 Result ✅ Accepted ⚡ Runtime: 0 ms (Beats 100%) 💾 Memory: 12.33 MB 🔖 Hashtags #LeetCode #Day11 #30DaysOfLeetCode #Python #LinkedList #DataStructures #Algorithms #CodingJourney #ProblemSolving #TechGrowth #SoftwareEngineering
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