🚀 Day 78 - 100DaysOfCode 1611. Minimum One Bit Operations to Make Integers Zero Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0. Use a loop to find the largest power of 2 (curr) that is ≤ n. Keep track of its position k. This identifies the leftmost 1 bit in n. Mathematical Formula for Powers of Two: For numbers like 1, 2, 4, 8, 16... (i.e., 2^k), the number of operations to make them 0 is: f(k) = 2^(k + 1) - 1 Divide the Number: Split n into two parts: The most significant bit: curr = 2^k The remaining part: n' = n XOR curr (This removes the highest bit from n.) Recursive Relationship: The answer for n is derived as: A(n) = f(k) - A(n') Here, f(k) = steps to reduce 2^k → 0 A(n') = steps to reduce the smaller remaining number to 0 Why Subtraction (−) Instead of Addition (+): Because n is already partially reduced compared to 2^k. Those smaller bits represent “progress,” so we subtract the steps already covered. Recursion: The function calls itself with the smaller number n'. This continues until n becomes 0. Bitwise Operations Used: << → left shift to compute powers of two (2^(k+1)). ^ → XOR to remove the highest set bit from n. Complexity: Time: O((log n)²) Space: O(log n) (recursion depth) 📌 #100DaysOfCode #Day78 #Leetcode Good rated question
"Day 78 - 100DaysOfCode: Minimum Bit Operations to Zero"
More Relevant Posts
-
💡 Day 92 of #100DaysOfCode Today I explored one of the fundamental problems in Binary Trees — checking whether two trees are identical 🌳 🔍 Problem: Given two binary trees, determine if they are the same in both structure and node values. 💻 Approach Used: I used recursion to solve the problem elegantly. The logic is simple yet powerful — 1️⃣ If both nodes are NULL, they are identical at that branch. 2️⃣ If one is NULL and the other isn’t, they differ. 3️⃣ Otherwise, check whether the current node values match and then recursively compare the left and right subtrees. 🧠 Key Insight: Recursion is a natural fit for tree problems — it mirrors the tree’s structure perfectly, allowing us to break down complex comparisons into smaller, easy-to-handle parts. ✅ Skills Strengthened: Recursive thinking Binary tree traversal concepts Structural comparison logic in C++
To view or add a comment, sign in
-
-
🔥 Day 120 of My DSA Challenge – Remove Linked List Elements 🔷 Problem : 203. Remove Linked List Elements 🔷 Goal : Remove all nodes from a linked list whose value equals a given val, and return the updated head. 🔷 Key Insight : This problem focuses on Linked List traversal and pointer manipulation, one of the most fundamental concepts in data structures. Directly removing nodes from a linked list can get tricky, especially when dealing with the head node itself. To simplify this, we use a dummy node technique — a smart approach to handle head removals gracefully. 🔷 Approach : 1️⃣ Create a dummy node (dummy) that points to the start of the list. 2️⃣ Use a pointer (tail) to build a new filtered list. 3️⃣ Traverse the original list using head: If head.val != val, link it to the new list. Otherwise, skip the node. 4️⃣ After traversal, ensure tail.next = null to avoid cycles. 5️⃣ Return dummy.next (new head). Time Complexity: O(n) Space Complexity: O(1) This problem reinforces : ✅ Pointer management ✅ Dummy node usage ✅ Clean and safe linked list manipulation When handling linked lists, think in pointers — not positions. Efficient traversal and clean linking make all the difference. ⚡ 120 days strong. One more concept mastered, one step closer to mastery. 🚀 #Day120 #DSA #100DaysOfCode #LeetCode #Java #LinkedList #Pointers #ProblemSolving #Algorithms #DataStructures #CodingChallenge #DeveloperJourney #EngineerMindset #LogicBuilding
To view or add a comment, sign in
-
-
#day21 of #30daysleetcodechallenge Solved: 410. Split Array Largest Sum Approach: 1. Algorithm: This code uses Binary Search on the Answer. Instead of trying to find where to split the array, it searches for the value of the "minimum largest sum" itself. 2. Search Space: The smallest possible "largest sum" is the largest single element in the array (this is the initial low). The largest possible "largest sum" is the total sum of the entire array (this is the initial high). The correct answer must lie between these two bounds. 3. Hypothesis (The mid Value): The mid value calculated in each step of the binary search ((low + high) / 2) represents a hypothetical answer. We test this mid to see if it's possible to split the array into k subarrays such that no subarray's sum exceeds mid. 4. Feasibility Check (The par function): The helper function par(nums, n, mid) checks this hypothesis. It greedily counts the minimum number of partitions (p) needed to split the array, given that no single partition's sum can be greater than mid. It does this by adding elements to a current sum until the next element would exceed mid, at which point it increments the partition count (p) and starts a new sum. 5. Adjusting the Search: If the par function returns a partition count partitions that is greater than k, it means our mid value (the max allowed sum) was too small. It forced us to make too many splits. We must try a larger potential answer, so we set low = mid + 1. 6. If partitions is less than or equal to k, it means our mid value is a valid (or possibly too large) answer. We try to find an even smaller valid answer by setting high = mid - 1. The loop continues until low converges on the smallest mid that works. Time Complexity: O(N * log(sum(arr[])-max(arr[])+1)) Space Complexity: O(1)
To view or add a comment, sign in
-
-
🔥 Day 117 of My DSA Challenge – Partition Array According to Given Pivot 🔷 Problem : 2161. Partition Array According to Given Pivot 🔷 Level : Medium 🔷 Goal : Rearrange an array so that — 1️⃣ Elements less than the pivot come first 2️⃣ Elements equal to the pivot come next 3️⃣ Elements greater than the pivot come last …and maintain relative order for smaller and larger elements. 🔷 Key Idea : The problem is a great test of array manipulation and partitioning logic — similar to what we see in the partition step of quicksort, but here the order must be stable (unchanged for equal categories). We can solve it cleanly using extra space and multiple passes: First collect elements < pivot Then elements == pivot Finally elements > pivot 🔷 Approach : 1️⃣ Initialize a result array res of same size. 2️⃣ Keep two pointers — left starts from the beginning for smaller elements. right starts from the end for larger elements. 3️⃣ Fill smaller elements from the start. 4️⃣ Fill larger elements from the end (in reverse order). 5️⃣ Fill the middle portion with the pivot. Time Complexity: O(n) Space Complexity: O(n) This problem strengthens your understanding of partitioning logic, stable ordering, and array construction — all fundamental to sorting algorithms and data arrangement. Small rearrangements. Big insights. Every element has its right place — in arrays and in life. ⚡ #Day117 #DSA #100DaysOfCode #LeetCode #Java #Arrays #ProblemSolving #CodingChallenge #Algorithms #DataStructures #LearningJourney #CodeEveryday #DeveloperMindset #EngineerInProgress
To view or add a comment, sign in
-
-
#day19 of #30daysleetcodechallenge Solved: 1011. Capacity To Ship Packages Within D Days Approach: 1. Binary Search on Answer: The core idea is to perform a binary search on the range of possible ship capacities, not on the weights array itself. 2. Define Search Space: The code establishes the search range for the capacity. 3. The minimum possible capacity (low) must be at least the weight of the heaviest single package (maxi). 4. The maximum possible capacity (high) is the total weight of all packages (sum), which would ship everything in one day. 5. Helper Function (func): This function acts as a "feasibility checker." Given a test capacity, it simulates the shipping process greedily, loading packages in order. It returns the total number of days it would take to ship all packages if the ship's capacity was limited to that amount. 6. Test the Midpoint: Inside the while loop, the code picks a potential capacity (mid) from the middle of the current low-high range. It uses func(mid) to find out how many days this capacity would require. 7. Adjust the Search Range: If the days required for mid capacity are less than or equal to the allowed days, it means this capacity is valid (or too big). The code then tries to find a smaller, still-valid capacity by setting high = mid - 1. If the days required are more than the allowed days, it means the mid capacity is too small. The code must increase the capacity by setting low = mid + 1. Time Complexity: O(N * log(sum(weights[]) - max(weights[]) + 1)) Space Complexity: O(1)
To view or add a comment, sign in
-
-
Data Structure and Algorithms Merge Two Sorted Lists. For my lab assignment, I solved the LeetCode problem “Merge Two Sorted Lists” using C++ linked lists and pointer manipulation. 🔹 Approach I Used: I compared the starting nodes of both lists, picked the smaller one as the head, and then iteratively attached the next smallest nodes using a pointer (curr). When one list ended, I simply linked the remaining nodes of the other list to complete the merge efficiently. 🔹 Key Concepts: Linked Lists Pointer updates Iterative merging Time Complexity: O(n + m) This assignment really helped me improve my understanding of linked list traversal and handling edge cases. 🎥 Video Explanation: [https://lnkd.in/df6nZs3w] Note: At first I thought merging lists would merge me instead—but thankfully only the code struggled, not me! #DSA #LabAssignment #LeetCode #C++ #CodingPractice #ProblemSolving #MergeTwoSortedLists
To view or add a comment, sign in
-
Data Structure and Algorithms Merge Two Sorted Lists For my lab assignment, I solved the LeetCode problem “Merge Two Sorted Lists” using C++ linked lists and pointer manipulation. 🔹 Approach I Used: I compared the starting nodes of both lists, picked the smaller one as the head, and then iteratively attached the next smallest nodes using a pointer (curr). When one list ended, I simply linked the remaining nodes of the other list to complete the merge efficiently. 🔹 Key Concepts: Linked Lists Pointer updates Iterative merging Time Complexity: O(n + m) This assignment really helped me improve my understanding of linked list traversal and handling edge cases. 🎥 Video Explanation: [https://lnkd.in/df6nZs3w] Note: At first I thought merging lists would merge me instead but thankfully only the code struggled, not me! #DSA #LabAssignment #LeetCode #C++ #CodingPractice #ProblemSolving #MergeTwoSortedLists
To view or add a comment, sign in
-
🚀Day 11/100-leetcode 35 solved - Problem statement :- 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. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [1,3,5,6], target = 5 Output: 2 Example 2: Input: nums = [1,3,5,6], target = 2 Output: 1 Example 3: Input: nums = [1,3,5,6], target = 7 Output: 4 Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums contains distinct values sorted in ascending order. -104 <= target <= 104
To view or add a comment, sign in
-
-
🚀 Day 184 of solving 365 medium questions on LeetCode! Continuing my journey of solving one LeetCode problem every day to sharpen my problem-solving and data structure skills. 🔥 Today's challenge: "Find Closest Node to Given Two Nodes" ✅ Problem: You’re given a directed graph represented by an array edges, where edges[i] points to another node or -1 if none. Given two nodes node1 and node2, find the node reachable from both such that the maximum distance from each starting node is minimized. ✅ Approach: Use BFS (or DFS) from both nodes to compute distances to every other node. Iterate through all nodes, checking which are reachable from both. Choose the node with the smallest max(distance from node1, distance from node2); if tie, pick smaller index. ✅ Key Insight: Precomputing distances separately avoids recomputation — a clean use of graph traversal + distance comparison. ✅ Complexity: Time: O(n) — since each node is visited at most twice. Space: O(n) — for distance arrays. 🔍 Check out my solution approach in the attached slides! 🔥 Flexing my coding skills until recruiters notice! #LeetCode365 #Graph #BFS #DFS #ProblemSolving #Algorithms #DataStructures
To view or add a comment, sign in
-
Everyone can be a Software Developer but few becomes Software Engineer. Data Structures and Algorithms are not just for learning but they allow us to use them according to our needs and write optimized and clean code. Some people tend to forget and just learn Data Structures and Algorithms for clearing the interview but they don't know how easy it would make their life as an engineer because development and engineering is totally different things. This type of content should be shared across the platform so that even a beginner who is new to LinkedIn could find these sources and try to learn to be best.
🚀 BCA Student @ Jamia Millia Islamia | Aspiring Full-Stack Developer (MERN) | DSA Enthusiast, solving problems daily 💻
🚀 Day 25 of my #100Daysofcode challenge - Implemented Linked List from Scratch in C++ Today I went back to the DSA fundamentals and implemented a Linked List completely from scratch using C++ ⚙️ 🔗 GitHub Repository: https://lnkd.in/eQxXHT9a Here’s what I built 👇 🧱 What’s Inside the Code: Node class → represents an element with data and next pointer List class → handles all the operations like 🔹 pushFront() & pushBack() — add elements to head/tail 🔹 insertNode() — insert at a specific position 🔹 popFront() & popBack() — delete nodes efficiently 🔹 search() — find element by value 🔹 printLinkedList() — visualize list elements 🔹 createLink_ListfromArray() — build linked list directly from an array 💡 Concepts Strengthened: ✅ Dynamic memory allocation (new, delete) ✅ Pointer manipulation ✅ Traversal, insertion, and deletion logic ✅ Object-oriented design (encapsulation and class-based structuring) 📚 Why I did this: Revisiting data structures helps reinforce problem-solving foundations. Understanding how a Linked List actually works internally gives me better control while tackling more advanced topics like stacks, queues, and graphs. ✨ Next Steps: Planning to extend this into Doubly Linked List and Circular Linked List implementations.
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