Day 57: Binary Breakdown ⚡ Problem 1404: Number of Steps to Reduce a Number in Binary Representation to One Today’s challenge: Divide by 2 if even, add 1 if odd. Repeat until you hit 1. The Strategy: • The Trap: Initially tried Integer.parseInt(), but the test cases hit me with strings longer than Integer.MAX_VALUE. Absolute poverty. 💀 • The Pivot: Switched to a single-pass traversal from right to left, tracking the carry. • Logic: If a bit + carry equals 1, it's an odd number, requiring 2 steps (add 1, then divide) and generating a new carry. Otherwise, it's just 1 step to divide. Moving from O(N) string conversions to a lean O(N) bit-by-bit logic. Big integers can't stop the streak. 🚀 #LeetCode #Java #BitManipulation #Algorithms #ProblemSolving #DailyCode
Reduce Binary Number to 1 with Bit Manipulation
More Relevant Posts
-
Day 82/100 – LeetCode Challenge ✅ Problem: #43 Multiply Strings Difficulty: Medium Language: Java Approach: Manual Multiplication with Result Array Time Complexity: O(n × m) Space Complexity: O(n + m) Key Insight: Multiply digits from right to left (least significant first). Store intermediate results in array where index i + j + 1 holds current digit. Handle carry by adding to previous index. Solution Brief: Edge case: if either number is "0", return "0". Created result array of size n1 + n2 (max possible digits). Nested loops multiply each digit of num1 with each digit of num2. Accumulated results with proper carry handling. Built final string skipping leading zeros. #LeetCode #Day82 #100DaysOfCode #Math #String #Java #Algorithm #CodingChallenge #ProblemSolving #MultiplyStrings #MediumProblem #Multiplication #Array #DSA
To view or add a comment, sign in
-
-
𝗧𝗼𝗱𝗮𝘆’𝘀 𝗶𝗻𝘁𝗲𝗿𝗲𝘀𝘁𝗶𝗻𝗴 𝗽𝗿𝗼𝗯𝗹𝗲𝗺: LeetCode 1980 – Find Unique Binary String Given n unique binary strings of length n, the task is to construct a binary string that does not exist in the list. The brute-force idea would explore up to (2^n) possibilities. But there’s a much cleaner insight: if we flip the i-th bit of the i-th string and build a new string from those flips, the result is guaranteed to differ from every string in the list. This technique comes from 𝗖𝗮𝗻𝘁𝗼𝗿’𝘀 𝗱𝗶𝗮𝗴𝗼𝗻𝗮𝗹 𝗮𝗿𝗴𝘂𝗺𝗲𝗻𝘁, a concept from mathematics that turns out to be surprisingly useful in algorithm design. Always enjoyable when a simple idea leads to an optimal 𝗢(𝗻) solution. #leetcode #algorithms #datastructures #problemSolving #softwareengineering #java
To view or add a comment, sign in
-
-
Headline: Cracking the "Largest Rectangle in Histogram" (LeetCode 84) 🚀 I just cleared this classic Hard problem with a 0ms runtime! The challenge is finding the largest area in a histogram in O(n) time. The secret sauce? A Monotonic Stack. By storing indices of bars in increasing order, we can identify the "boundary" for each height in a single pass. Key takeaway: Choosing the right data structure (like a Stack) can turn an expensive O(n^2) search into a lightning-fast linear solution. 👨💻 #LeetCode #Java #Algorithms #DataStructures #CodingLife
To view or add a comment, sign in
-
-
Day 72: Binary Search Squared 🏔️ Problem 3296: Minimum Number of Seconds to Make Mountain Height Zero Today’s problem was a masterclass in optimization. The goal: reduce a mountain's height to zero using workers who take progressively more time for each unit of height they remove. The Strategy: • Binary Search on Answer: Since the time needed is monotonic, I used binary search to find the minimum seconds required to finish the job. • Nested Binary Search: Inside that loop, I ran a second binary search for each worker to calculate the maximum height they could handle within that time limit. • Efficiency: This "Double Binary Search" approach kept the runtime lean even with a massive search space up to 10^16. Solving a "Binary Search inside a Binary Search" problem is a great way to test your grip on time complexity. It’s all about finding that optimal boundary. 🚀 #LeetCode #Java #BinarySearch #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
Day 85/100 – LeetCode Challenge ✅ Problem: #226 Invert Binary Tree Difficulty: Easy Language: Java Approach: Recursive DFS (Divide and Conquer) Time Complexity: O(n) Space Complexity: O(h) where h = tree height Key Insight: Swap left and right child at every node, then recursively invert both subtrees. Classic recursion problem — made famous by Google interview story. Solution Brief: Base case: if root is null, return null. Swap left and right children using temporary variable. Recursively call invertTree on left and right subtrees. Return the root (now inverted). #LeetCode #Day85 #100DaysOfCode #Tree #Java #Algorithm #CodingChallenge #ProblemSolving #InvertBinaryTree #EasyProblem #DFS #Recursion #DSA
To view or add a comment, sign in
-
-
Yesterday's problem was about searching in a rotated array. Today's challenge was slightly different: What if we just needed to find the smallest number in that rotated array? 🚀 Day 76/365 — DSA Challenge Solved: Find Minimum in Rotated Sorted Array The Problem You're given a sorted array that has been rotated at some unknown pivot. 💡 My Approach This problem can be solved using Binary Search. Key observation: In a rotated sorted array, the smallest element is where the rotation happened. Steps: 1️⃣ Find the middle element 2️⃣ Compare it with the right element: nums[mid] > nums[right] 3️⃣ If true → the minimum must be in the right half 4️⃣ Otherwise → the minimum is in the left half (including mid) Complexity ⏱ Time: O(log n) 📦 Space: O(1) Day 76/365 complete. 💻 289 days to go. Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #BinarySearch #Algorithms #LearningInPublic
To view or add a comment, sign in
-
-
Day 72/100 – LeetCode Challenge ✅ Problem: #7 Reverse Integer Difficulty: Medium Language: Java Approach: Digit Extraction with Overflow Check Time Complexity: O(log₁₀ x) Space Complexity: O(1) Key Insight: Reverse integer by repeatedly extracting last digit and building result. Critical: Check overflow before final cast using long to detect > Integer.MAX_VALUE or < Integer.MIN_VALUE. Solution Brief: Extracted digits using modulo 10. Built reversed number step by step in long to detect overflow. After loop, divided by 10 to remove extra multiplication. Checked if result fits in 32-bit integer range. Handled sign separately at the end. #LeetCode #Day72 #100DaysOfCode #Math #Java #Algorithm #CodingChallenge #ProblemSolving #ReverseInteger #MediumProblem #Overflow #DigitManipulation #DSA
To view or add a comment, sign in
-
-
Day 64: The Art of Alternating 🏁 Problem 1758: Minimum Changes To Make Alternating Binary String Today was about finding the shortest path to a perfect pattern. The goal: transform a binary string into an alternating sequence (0101... or 1010...) with the minimum number of flips. The Strategy: • Pattern Prep: Recognized that only two target patterns exist for any given length. • The Comparison: Pre-generated both ideal patterns and ran a head-to-head comparison against the original string. • The Result: Counted the mismatches for both scenarios and returned the minimum. Ngl, generating two full arrays just to compare bits is a bit of a memory flex, but it makes the logic crystal clear. Sometimes visualizing the "perfect" state is the easiest way to fix the current one. 🚀 #LeetCode #Java #StringManipulation #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
Day 19 of Daily DSA 🚀 Solved LeetCode 2089: Find Target Indices After Sorting Array ✅ Approach: Instead of actually sorting the array, I counted: elements less than the target elements equal to the target The starting index is determined by how many elements are smaller than the target, and then indices are built for all equal elements. Simple counting → no extra sorting needed 💡 ⏱ Complexity: • Time: O(n) — single pass • Space: O(1) — excluding output list 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 44.83 MB (Beats 83.41%) A neat example of how thinking beyond “just sort it” can lead to cleaner and faster solutions. #DSA #LeetCode #Java #ProblemSolving #DailyCoding #Consistency #Arrays
To view or add a comment, sign in
-
-
Day 82/365 – Shuffle an Array A classic problem that teaches **true randomness** using the Fisher-Yates algorithm. 🔍 **Problem** Design a system to: * Shuffle an array randomly * Reset it back to original 👉 Every permutation must be **equally likely** 💡 **Key Insight** Use **Fisher-Yates Shuffle** (optimal & unbiased) 🧠 **Approach** Iterate from end → start: 1️⃣ Pick random index `j` from `[0, i]` 2️⃣ Swap `i` and `j` This guarantees uniform randomness. ⚡ **Why not random swaps?** 👉 Simple random swapping leads to **biased results** 👉 Fisher-Yates ensures **equal probability** #Day82 #365DaysOfCode #LeetCode #Randomization #Algorithms #DSA #CodingInterview #Java #ProblemSolving
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