✨ Day 5 of my LeetCode streak! Today I solved another interesting problem that taught me a cool bit manipulation trick 😎 💡 Problem: Smallest Number With All Set Bits Greater Than or Equal to N 📘 Statement: You are given a positive number n. Return the smallest number x greater than or equal to n, such that the binary representation of x contains only set bits (all 1s). Example: Input: n = 5 Output: 7 Explanation: Binary of 7 → 111 🧠 My Thought Process: At first, I noticed that numbers like 1 (1), 3 (11), 7 (111), 15 (1111) all have binary 1s only. So, the idea was simple 👇 Keep generating numbers like these (111...) until it becomes greater than or equal to n. To do that efficiently, I used bit manipulation: Start from mask = 1 Keep doing mask = (mask << 1) | 1 Stop when mask >= n The trick (mask << 1) | 1 means: Shift bits left (multiply by 2) Add one 1 at the end of the binary number 💻 Code (Java): class Solution { public int smallestNumber(int n) { int mask = 1; while (mask < n) { mask = (mask << 1) | 1; // shift left, add 1 at the end } return mask; } } 🧩 Example Dry Run: For n = 10: mask = 1 → 3 → 7 → 15 As soon as mask becomes 15 (>=10), that’s our answer ✅ Binary of 15 → 1111 🔍 Key Takeaways: Learnt how bit manipulation can make problems simpler and faster ⚡ Understood how left shift (<<) and bitwise OR (|) can be combined to create binary patterns Another cool use of binary logic to solve what looks like a simple math problem! 🗓️ LeetCode Streak: Day 5 / Consistency > Perfection 🔥 Every day I’m learning something new — one problem at a time. #LeetCode #100DaysOfCode #Java #BitManipulation #CodingJourney #ProblemSolving #Consistency
Solved LeetCode problem using bit manipulation trick
More Relevant Posts
-
💻 LeetCode 50 Days Challenge — Day 5: Search Insert Position Day 5 of my #LeetCode50DaysChallenge ✅ Today’s problem was about finding the correct insertion index in a sorted array efficiently — Search Insert Position ✨ 🧩 Problem: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. The goal is to achieve a runtime complexity of O(log n). 💡 Approach: I implemented a binary search approach. The idea is to use two pointers (left and right) to narrow down the range. If the middle element is less than the target, move the left pointer up. Otherwise, move the right pointer down. Once the pointers converge, the left index represents the correct insertion position. This method ensures an efficient and clean solution, making use of binary search logic rather than linear iteration. ⏱️ Time Complexity: O(log n) 📊 Example: Input: nums = [1, 3, 5, 6], target = 2 Output: 1 “Small steps every day lead to big progress — keep showing up!” 💪 #LeetCode #CodingChallenge #Day5 #ProblemSolving #Java #SoftwareDevelopment #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 63 of My LeetCode journey 🚀 Problem : Custom Sort String Today’s problem was interesting because instead of sorting using normal alphabetical order, we sort the given string based on a custom priority order. 🧠 Problem Understanding Given: order → defines priority of characters. str → the input string which needs to be rearranged. Goal: ✅ Arrange characters of str based on the sequence defined in order. ✅ Characters not present in order should appear at the end (any order). 💡 Approach (Simple & Efficient) Count frequency of each character in str. First append characters following the order. Then append remaining characters. Time Complexity: O(n) Space Complexity: O(1) (fixed array size for 26 letters) ✨ Learnings Sometimes the problem isn't about sorting, but about following a custom priority. Frequency counting is extremely powerful for character-based problems. StringBuilder → best way to build strings efficiently in Java. #leetcode #coding #dsa #java #100DaysOfCode #day63 #learningEveryday #problemSolving
To view or add a comment, sign in
-
-
🚀 Day 68 of #100DaysOfChallenge Today's problem: 3461. Check If Digits Are Equal in String After Operations I (LeetCode - Easy) This problem was a fun blend of pattern observation and modular arithmetic — a great reminder that even simple-looking questions can strengthen your logical flow and coding discipline on LeetCode. 🧩 Problem Overview: We’re given a string of digits, and in each step, we repeatedly calculate the sum of every pair of consecutive digits modulo 10, until only two digits remain. Finally, we check whether those two digits are equal. 💡 My Approach: Used a straightforward simulation approach — repeatedly computing new strings of digits using modular arithmetic until only two digits were left. It’s simple, direct, and performs efficiently for short strings. ⚙️ Language: Java ⚡ Runtime: 8 ms (Beats 72.03%) 💾 Memory: 44.67 MB (Beats 69.77%) ✅ Result: Accepted — 706 / 706 test cases passed Every daily problem adds another layer of precision and confidence. Consistency isn’t just about coding every day — it’s about learning something new with every attempt. 🌱 On to the next challenge 💪 #100DaysOfCode #LeetCode #ProblemSolving #Java #CodingChallenge #Programming #DeveloperJourney #LearningEveryday #TechMindset #Consistency
To view or add a comment, sign in
-
-
✅ Day 64 of LeetCode Medium/Hard Edition Today’s challenge was “Minimum Flips to Make a Binary String Monotone Increasing” — a brilliant mix of Dynamic Programming and binary state transitions 💡💻 📦 Problem: A binary string is monotone increasing if it consists of some number of 0s (possibly none) followed by some number of 1s (possibly none). We can flip any bit (0 → 1 or 1 → 0). Return the minimum number of flips required to make the string monotone increasing. 🔗 Problem Link: https://lnkd.in/grfy-BmC ✅ My Submission: https://lnkd.in/gKqQMxFG 💡 Thought Process: This problem can be visualized as maintaining two phases in the string — a sequence of 0s followed by a sequence of 1s. At each position, we decide whether to flip the current bit or transition to the next phase. We use recursion + memoization to find the minimal number of flips. Steps: 1️⃣ Define a recursive function helper(idx, bit) where bit represents the current phase (0-phase or 1-phase). 2️⃣ For each character: • If in 0-phase and current bit is '1', either flip it to '0' or transition to 1-phase. • If in 1-phase and current bit is '0', you must flip it to '1'. 3️⃣ Memoize results in dp[idx][bit] to avoid recomputation. 4️⃣ Return the minimal flips from start to end. ⚙️ Complexity: ⏱ Time: O(n × 2) — two states per index 💾 Space: O(n × 2) — due to memoization #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #ProblemSolving #Java #CodingChallenge
To view or add a comment, sign in
-
-
✨ Just Implemented LeetCode challenges — “Minimum Window Substring” using Java! This problem truly sharpened my understanding of the Sliding Window technique and taught me how efficient algorithms depend on balancing two moving pointers 🧠💻 Key Steps: Initialization: Create a frequency map (need) for characters in T. Initialize a counter (required) with T's length. 2. Expansion (Right Pointer): The right pointer expands the window one character at a time. 3.Contraction (Left Pointer): Once required is 0 (a valid window is found), the inner while loop starts contracting the window from the left. 4. Result: After the entire string $S$ is traversed, return the minimum window substring found ⚙️ Time Complexity: O(n) — Each character is processed at most twice (once by right and once by left). 🧠 Space Complexity: O(1) — Constant space, since the frequency array size is fixed (128 ASCII characters). 🔑 Takeaway: Efficient coding isn’t just about writing code that works — it’s about writing code that adapts smartly to changing conditions. 🖼️ Caption for Code Image “Sliding windows, shifting focus — finding clarity through logic 🪟💡” #LeetCode #Java #CodingChallenge #ProblemSolving #DataStructures #Algorithms #LearningJourney #SoftwareEngineering #WomenInTech
To view or add a comment, sign in
-
-
💻 LeetCode 50 Days Challenge — Day 3: Remove Duplicates from Sorted Array Day 3 of my #LeetCode50DaysChallenge ✅ Today’s problem was about array manipulation — Remove Duplicates from Sorted Array ✨ 🧩 Problem: Given an integer array nums sorted in non-decreasing order, remove duplicates in-place such that each unique element appears only once. The relative order of the elements should remain the same. 💡 Approach: This problem is a classic two-pointer approach! One pointer i keeps track of the last unique element’s position. The other pointer j iterates through the array. Whenever a new element is found (nums[i] != nums[j]), we move it forward by incrementing i and assigning nums[i] = nums[j]. In the end, i + 1 gives the count of unique elements. A simple yet elegant technique to modify arrays in-place! ⏱️ Time Complexity: O(n) 📊 Example: Input: [0,0,1,1,1,2,2,3,3,4] Output: [0,1,2,3,4] Consistency is the secret ingredient to progress! 🌱 Each problem solved adds another brick to the wall of mastery 💪 #LeetCode #CodingChallenge #Day3 #ProblemSolving #Java #SoftwareDevelopment #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
💻 Day 7: Back in the DSA Game! 🚀 After a short break (hello, Day 5 gap!), I'm excited to share my latest coding win: conquering LeetCode's #1 Two Sum problem with a highly optimized HashMap approach! This is a classic for a reason. Moving beyond the brute-force O(n^2)solution to the O(n) one-pass solution is a core step in algorithm mastery. The O(n) One-Pass HashMap Solution ✨ The key to efficiency here is using the HashMap to store the numbers we've already seen and their indices. In a single pass, for every number, we calculate its required complement (the value needed to hit the target). If the complement is already in the map, we've found our pair! If not, we add the current number and its index to the map for future checks. Code: public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> numMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; int complement = target - num; if (numMap.containsKey(complement)) { return new int[]{numMap.get(complement), i}; } numMap.put(num, i); } return new int[]{-1, -1}; } The Result 🎯 My implementation achieved an Accepted status with a 2 ms runtime, beating 99.12% of Java submissions! The efficiency of the O(n) solution clearly paid off. Runtime: 2 ms (Beats 99.12% of users) Persistence over perfection! Even with a gap, the momentum is back. What are your favorite "must-know" LeetCode patterns after Two Sum? Let me know in the comments! 👇 #DataStructures #Algorithms #LeetCode #TwoSum #Java #CodingChallenge #TechSkills
To view or add a comment, sign in
-
-
🚀 Day 73 of #100DaysOfCode Today I solved LeetCode 3346 – Maximum Frequency of an Element After Performing Operations I 🧩 This problem was all about logical range manipulation — figuring out how many elements could be converted into the same number when each element can be modified by ±k, but with a limited number of allowed operations. At first, it felt similar to the “most frequent element” sliding window problem, but the twist here was controlling how many elements can be changed, not just the total cost. After a few failed attempts (and a battle with edge cases 😅), I finally implemented a correct solution using the difference array + prefix sum approach. 💡 Key Takeaways: Think in terms of ranges, not just differences. Prefix-sum (difference map) logic is incredibly powerful for interval counting. Always recheck constraints — “number of operations” vs “total cost” makes a huge difference! Here’s a snippet from my final Java solution: int achievable = Math.min(running, same + numOperations); ans = Math.max(ans, achievable); It’s small details like these that make problem-solving such a rewarding process 💪 #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving #DSA #LearningEveryday
To view or add a comment, sign in
-
-
📌 Day 18/100 - Valid Palindrome (LeetCode 125) 🔹 Problem: Determine whether a string reads the same forward and backward, ignoring case and non-alphanumeric characters. 🔹 Approach: Implemented a two-pointer technique. Skipped all non-alphanumeric characters. Compared characters from both ends in lowercase. Returned true if all matched, otherwise false. 🔹 Key Learning: Two-pointer method keeps logic clean and efficient. Character handling is key when data isn’t uniform. Time complexity: O(n), Space complexity: O(1). Sometimes, solving elegantly is better than solving fast. ✨ #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney
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