Hello Everyone, Day 20 / #100DaysOfCode LeetCode 3314 — Construct the Minimum Bitwise Array I (Easy) Problem (in short): You’re given an array nums of prime integers. Construct an array ans such that for every index i: ans[i] OR (ans[i] + 1) = nums[i] And among all valid choices, minimize ans[i]. If it’s impossible, return -1 for that index. Key Observation: For any number x: x OR (x + 1) turns all trailing 0s in x into 1s until the first 1 bit blocks the carry. So to reach a given prime p, x must: - Have all bits set where p has 1s - Except exactly one bit, which is flipped to allow (x + 1) to complete the OR Why some values are impossible: - If p has only one set bit (e.g., 2 → 10₂), - there’s no smaller x such that: x OR (x + 1) = p So the answer is -1. Minimization Strategy: To get the smallest possible x, we: - Start from x = p - 1 - Remove the lowest set bit from p - This guarantees (x | (x + 1)) = p while keeping x minimal Implementation-wise, this boils down to bit-walking using powers of two. Complexity: - Time: O(n · log(max(nums))) - Space: O(n) #Leetcode #DSA #Java
Construct Minimum Bitwise Array with Prime Integers
More Relevant Posts
-
🚀 How a DTO Saved Me in Spring Boot I had a form that needed to save data into two tables from one page. Binding directly to two entities? Errors everywhere. 😅 Solution? DTO. I created a DTO holding all fields, bound the form to it, and then mapped it to the two entities. Result: clean code, no binding errors, form submits perfectly. 💥 Lesson: Sometimes a simple DTO is all it takes to fix complex binding problems. #SpringBoot #Java #DTO #BackendDevelopment #DeveloperLife
To view or add a comment, sign in
-
#200DaysOfCode – Day 117 Subsets (Power Set) using Bit Manipulation Problem: LeetCode 78 – Subsets Task:- Given an integer array of unique elements, return all possible subsets (the power set). Example: Input: nums = [1, 2, 3] Output: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]] My Approach (Bit Manipulation): Observed that for an array of size n, total subsets = 2^n. Used numbers from 0 to (2^n - 1) as binary masks. Each bit position represents whether an element is included (1) or excluded (0) in the subset. Iterated through each mask and built subsets accordingly. Complexity: Time Complexity: O(n * 2^n) Space Complexity: O(2^n) Bit manipulation is not just about low-level tricks it can provide elegant and efficient solutions to problems like generating subsets. Once you see the binary pattern, the solution becomes surprisingly intuitive. #LeetCode #Java #BitManipulation #DSA #ProblemSolving #TakeUForward #CodingJourney #200DaysOfCode #PowerSet #CleanCode
To view or add a comment, sign in
-
-
🚀 Day 23 / 100 | Add Two Numbers -Approach : O(n) - Traverse both linked lists simultaneously. - Maintain a carry variable to handle sums that are greater than or equal to 10. - Use a ans node to simplify the construction of the result list. - At each step, compute the sum as: sum = val1 + val2 + carry. - Update the carry as carry = sum / 10 and store sum % 10 in a new node. - Continue this process until both lists and the carry are exhausted. - Finally, return ans.next. #100DaysOfCode #LeetCode #Java #DSA #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 9 — LeetCode Progress (Java) 🔹 Next Greater Element I → Built a mapping using HashMap by scanning the second array and identifying the next greater value for each element, then used it to construct the result efficiently without repeated searches. ━━━━━━━━━━━━━━━━━━━━ Today’s focus was on improving array traversal logic and understanding how mapping relationships between elements can simplify future lookups. Instead of brute force comparisons for every query, pre-processing the array helped reduce unnecessary checks and made the solution cleaner. 💭 Takeaways: • Precomputing relationships using hashing can drastically reduce complexity. • Writing readable loops is just as important as getting the correct answer. • Small optimizations in logic structure make solutions easier to scale later. Consistency continues. One step closer to stronger fundamentals. 🔥 #LeetCode #DSA #Java #CodingJourney
To view or add a comment, sign in
-
-
📘 LeetCode Daily — Problem #3634 Worked through LeetCode 3634 today using the Sliding Window pattern. The interesting part wasn’t just arriving at the solution, but understanding why this approach fits and how implementation details matter. One key takeaway was recognizing when to switch from int to long to prevent overflow—something that’s easy to miss but critical for correctness. Problems like this reinforce that efficient logic and careful data handling go hand in hand. #LeetCode #SlidingWindow #DSA #Java #ProblemSolving #DailyPractice
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode | Day 37 📌 LeetCode – Remove Duplicates from Sorted List Today I solved a classic Linked List problem focused on pointer manipulation and in-place updates. Given the head of a sorted linked list, remove all duplicates so that each element appears only once and return the modified list. 💡 Approach Since the list is already sorted, duplicate values appear next to each other. Instead of using extra space like a HashSet, I used a single pointer to traverse the list: ✔️Compare the current node with the next node ✔️If values are equal → skip the duplicate ✔️Otherwise → move forward ✔️Continue until reaching the end ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) Every linked list problem improves pointer confidence step by step 💪 #Java #DataStructures #LinkedList #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
LeetCode Problem Solved | #1209. Remove All Adjacent Duplicates in String II Today I worked on LeetCode 1209, which is a great extension of the classic adjacent-duplicate problem and a perfect example of the stack pattern in DSA. 🧠 Problem Summary Given a string s and an integer k, repeatedly remove k adjacent identical characters until no more removals are possible. Example: Input: s = "deeedbbcccbdaa", k = 3 Output: "aa" 💡 Approach (Using Stack) 1. Traverse the string character by character 2. If the current character matches the stack top -> increment count 3. If count reaches k -> pop from stack 4. Otherwise -> push a new Pair 5 .Finally, rebuild the string from the stack #LeetCode #DSA #Java #Stack #ProblemSolving #CodingPractice
To view or add a comment, sign in
-
-
Day 24 / #100DaysOfCode LeetCode 1877 — Minimize Maximum Pair Sum in Array (Medium) Problem (short): Given an array of even length, pair up all elements such that the maximum pair sum is minimized. Each element must be used exactly once. Key Insight: - To minimize the maximum pair sum, we must balance extremes. - Pairing large numbers together increases the maximum. - Pairing small numbers together wastes the chance to offset large values. So the optimal strategy is: - Sort the array - Pair the smallest with the largest, second smallest with second largest, and so on - Track the maximum among these pair sums This greedy pairing ensures no pair becomes unnecessarily large. Approach: 1. Sort the array 2. Use two pointers from both ends 3. For each pair, compute sum and update the maximum - Time Complexity: O(n log n) - Space Complexity: O(1) (ignoring sort space) #Leetcode #DSA #Java
To view or add a comment, sign in
-
-
Day 33 / #100DaysOfCode LeetCode 3013 — Divide an Array Into Subarrays With Minimum Cost II (Hard) Problem (short): Given an array nums, divide it into k subarrays such that: - The first subarray must start at index 0 - The distance between the start of the 2nd and kth subarray is at most dist - The total cost (sum of starting elements of all subarrays) is minimized This is the Hard follow-up of Part I, and the constraints make brute force impossible. Key Challenge: Once k becomes variable, we are no longer choosing just 2 elements. We must dynamically maintain the minimum sum of (k-2) valid starting elements inside a moving window. This is where simple sorting or greedy breaks. Core Idea / Observation: - nums[0] is always included - For each possible ending index, we need: • the smallest (k-2) elements from a sliding window • fast insertion and deletion • fast access to the smallest elements This naturally leads to a two-multiset (two TreeMap) strategy. Approach: 1. Fix nums[0] as the first subarray 2. Use two TreeMaps: • st1: stores the smallest (k-2) elements (contributes to sum) • st2: stores the remaining elements 3. Maintain balance using: • automatic shifting between maps • invariant: st1 always contains exactly (k-2) smallest elements 4. Slide the window while respecting the dist constraint 5. At each step: • compute current cost = nums[0] + sum(st1) + current element • update minimum I did take help from the editorial here — to understand how to maintain the invariant correctly. This problem is more about data-structure discipline than raw logic. Complexity: - Time: O(n log n) - Space: O(k) (due to TreeMaps) #Leetcode #DSA #Java
To view or add a comment, sign in
-
-
Day 60/100 – LeetCode Challenge ✅ Problem: #67 Add Binary Difficulty: Easy Language: Java Approach: Reverse Iteration with Carry Time Complexity: O(max(n, m)) Space Complexity: O(max(n, m)) Key Insight: Binary addition follows same rules as decimal: Sum bits + carry Result bit = sum % 2 New carry = sum / 2 Solution Brief: Iterated from rightmost bits of both strings. Tracked carry and built result from right to left using StringBuilder. Reversed final string for correct order. #LeetCode #Day60 #100DaysOfCode #Binary #Java #Algorithm #CodingChallenge #ProblemSolving #AddBinary #EasyProblem #StringManipulation #BitManipulation #DSA
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