🔹 Day 51: Power of Two (LeetCode #231) 📌 Problem Statement: Given an integer n, return true if it is a power of two, otherwise return false. An integer n is a power of two if there exists an integer x such that n == 2^x. ✅ My Approach: I checked whether the number can be continuously divided by 2 until it reaches 1: If n is less than or equal to 0, it’s not a power of two. While n is divisible by 2, divide it by 2. If the result equals 1, then it’s a power of two; otherwise, it’s not. 📊 Complexity: Time Complexity: O(log n) — each division by 2 reduces n exponentially. Space Complexity: O(1) ⚡ Submission Stats: Runtime: 1 ms (Beats 33.54%) Memory: 41.04 MB (Beats 41.60%) 💡 Reflection: This problem strengthened my understanding of how powers of two follow a binary pattern. It also reminded me that bit manipulation (n > 0 && (n & (n-1)) == 0) can offer an even faster alternative. ⚡ #LeetCode #Java #Math #BitManipulation #100DaysOfCode #Day51
How to check if a number is a power of two in Java
More Relevant Posts
-
🚀 Just Solved LeetCode #1367 — Linked List in Binary Tree 📘 Problem: Given the head of a linked list and the root of a binary tree, determine whether all the elements of the linked list appear as a downward path in the binary tree. Downward means starting from any node and moving only to child nodes. Example: Input → head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output → true Explanation → Nodes in blue form a subpath in the binary tree. 🧠 My Approach: I used recursion to check whether the linked list sequence can be found starting from any node in the binary tree. 1️⃣ For each node in the tree, check if the list starting from `head` matches the downward path from that node. 2️⃣ If not, recursively check the left and right subtrees. 3️⃣ Used a helper function `checkPath()` to verify if a valid path continues as the recursion goes deeper. 💡 What I Learned: ✅ How to combine linked list and binary tree traversal logic ✅ How recursion can efficiently check multiple starting points ✅ Improved my understanding of tree path traversal and backtracking logic #LeetCode #Java #DSA #BinaryTree #LinkedList #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
✅ LeetCode Day 45 — Problem #162: Find Peak Element 🚀 Approach: I applied the Binary Search technique to locate a peak element efficiently. Initialize two pointers l and r. Compute the middle index m. If nums[m] < nums[m + 1], it means the peak lies on the right side → move l = m + 1. Otherwise, the peak lies on the left or at m → move r = m. Continue until l == r, which gives the index of the peak element. ⏱️ Time Complexity: O(log n) 💾 Space Complexity: O(1) 💡 Learning: Binary search can be applied beyond just sorted arrays — it’s a powerful pattern for problems with a “direction” property! #LeetCode #Day45 #DSA #BinarySearch #ProblemSolving #Java #100DaysOfCode #LearningEveryday #CodingChallenge
To view or add a comment, sign in
-
-
📌 Day 38/100 – Make array elements equal to zero (LeetCode 3354) 🔹 Problem: Given an integer array nums, each element can be a number or zero. You need to find how many zeros in the array can be replaced by either +1 or -1 such that the total sum on both sides of that zero (left and right) remains balanced or differs by 1. 🔹 Approach: First, calculate the total sum s of all elements. Maintain a prefix sum l as you iterate. For each zero: If l * 2 == s, both +1 and -1 replacements are valid → add 2 to ans. If |l * 2 - s| == 1, only one replacement is valid → add 1 to ans. Return the total count ans. 🔹 Key Learning: Prefix sums simplify balance-based problems. Comparing 2 * prefixSum with total sum helps quickly check left-right equilibrium. 🔹 Complexity: Time: O(n) — single pass through array Space: O(1) — no extra storage used 🔹 Hashtags: #Day38Of100 #LeetCode3354 #100DaysOfCode #Java #DSA #ProblemSolving #PrefixSum #CodingChallenge
To view or add a comment, sign in
-
-
💻 #Day486 (DSA) – LeetCode 3370: Smallest Number With All Set Bits 🔥 🚀 Problem Summary: Given a positive integer n, find the smallest number x ≥ n such that the binary representation of x contains only set bits (1s). 🧩 Examples: Input: n = 5 Output: 7 → Binary: 111 Input: n = 10 Output: 15 → Binary: 1111 Input: n = 3 Output: 3 → Binary: 11 💡 Intuition: To find the smallest number having all bits set, we can compute numbers like: 1 → (1), 3 → (11), 7 → (111), 15 → (1111), 31 → (11111)... and pick the smallest one ≥ n. 🧠 Approach: Keep generating (1 << k) - 1 until the result is ≥ n. That number will be our answer ✅ 🧩 Code (Java): class Solution { public int smallestNumber(int n) { int x = 1; while (x < n) { x = (x << 1) | 1; // shift and set next bit } return x; } } 🕒 Time Complexity: O(log n) 💾 Space Complexity: O(1) ✨ Key Learning: Mastery in bit manipulation 🧠 Smart usage of left shift and bitwise OR Understanding how binary patterns grow 🏷️ Tags: #LeetCode #DSA #BitManipulation #CodingChallenge #ProblemSolving #Java #DeveloperJourney #Algorithms #KeepLearning #CodeEveryday #TechCommunity 💬 Question for you: If you had to generalize this for the next “all-set bit number” above any given n, how would you optimize it? 🤔
To view or add a comment, sign in
-
-
🚀Day 43/100 - Problem of the day :- Number of Substrings With Only 1s. 🎯 Goal :- To solve the problem of counting the number of substrings consisting only of consecutive ‘1’s in a binary string, while ensuring high efficiency and optimal performance. 💡 Core Idea :- Traverse the string once and maintain a running count of continuous ‘1’s. Every time you encounter ‘1’, increase the streak; If you hit ‘0’, add the triangular count of the streak to the answer and reset. Formula used: 👉 For a streak of length k, total substrings = k × (k + 1) / 2 📌 Key Takeaway:- Efficient linear traversal avoids unnecessary nested loops. Counting consecutive segments instead of checking all substrings improves performance drastically. Perfect example of how mathematical insight + simple iteration = optimized solution. 🧠 Space Complexity:- O(1) — Only a few variables used (constant additional memory). ⚡ Time Complexity :- O(n) — Single pass through the string. #100DaysChallenge #DSA #Java #Day43 #CodingJourney #ProblemSolving #Leetcode
To view or add a comment, sign in
-
-
✨ LeetCode 104 – Maximum Depth of Binary Tree Today I solved another interesting Binary Tree problem 🌳 🧩 Problem Summary: Given the root of a binary tree, we need to find its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf. 💡 Intuition: We can use recursion — At each node, the maximum depth is 1 + max(depth of left subtree, depth of right subtree). If the node is null, the depth is 0. 🧠 Approach: ✔️ Use a simple DFS traversal ✔️ Recursively calculate left and right subtree depths ✔️ Add 1 for the current node 🕒 Complexity: Time: O(N) — visit each node once Space: O(H) — recursion stack (H = height of the tree) #LeetCode #Java #DSA #BinaryTree #Recursion #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 LeetCode 3370 — Smallest Number With All Set Bits Today I solved an interesting problem that tested my bit manipulation intuition 🧠 🧩 Problem: Given a positive integer n, find the smallest number x ≥ n such that the binary representation of x contains only set bits (1s). 💡 My Thought Process: I realized that numbers with all bits set follow a simple pattern: 1 -> 1 3 -> 11 7 -> 111 15 -> 1111 31 -> 11111 Each is basically (power of 2) - 1 🔥 So my goal became: ➡️ Move n to the next power of two, ➡️ Then subtract 1, to make all bits below it set. But instead of doing it mathematically, I wanted to do it bit-by-bit 👇 🔍 How it works: 1️⃣ From MSB to LSB, keep only the first 1 bit and clear the rest. 2️⃣ Left shift to reach the next power of 2. 3️⃣ Subtract 1 to make all bits set. Example: n = 10110 (22) → n = 10000 → n << 1 = 100000 → n - 1 = 11111 (31) ✅ 💬 Takeaway: Sometimes, the most elegant solutions are the ones where you play directly with bits rather than formulas. Bit manipulation is like solving puzzles at the binary level — small details, huge insights ⚙️ #LeetCode #Java #BitManipulation #DSA #ProblemSolving #CodingJourney #100DaysOfCode #LearnEveryday
To view or add a comment, sign in
-
-
🚀 Just Solved LeetCode #110 — Balanced Binary Tree 📘 Problem: Given the root of a binary tree, determine if it is height-balanced — that is, for every node, the height difference between the left and right subtree should not exceed 1. Example: Input → [3,9,20,null,null,15,7] Output → true 🧠 My Approach: I used a bottom-up recursive approach to check balance efficiently. 1️⃣ For each node, I calculated the height of its left and right subtrees. 2️⃣ If any subtree was unbalanced, I returned -1 immediately to stop further checks. 3️⃣ If the height difference between left and right subtrees was greater than 1, I marked the tree as unbalanced. 4️⃣ Otherwise, I returned the height of the current node as 1 + max(left, right). This approach ensures every node is visited only once — making it O(n) in time complexity. 💡 What I Learned: ✅ The difference between top-down and bottom-up recursion in tree problems ✅ How to optimize recursion by early termination when imbalance is detected ✅ Strengthened my understanding of recursive depth and height calculation in binary trees #LeetCode #Java #DSA #BinaryTree #CodingJourney
To view or add a comment, sign in
-
-
🔢 Day 47 of #LeetCode100DaysChallenge Solved LeetCode 79: Word Search — a classic backtracking problem that beautifully blends recursion and grid traversal. 🧩 Problem: Given a 2D grid of characters and a word, determine if the word can be formed using sequentially adjacent cells (up, down, left, right), where each cell can be used only once. 💡 Approach Used — Backtracking (DFS): 1️⃣ Start from each cell that matches the first character. 2️⃣ Explore in all four directions recursively. 3️⃣ Temporarily mark visited cells to avoid reuse. 4️⃣ If the entire word is matched, return true; otherwise, backtrack. ⚙️ Complexity: Time: O(N × 4ᴸ) — where N is the total number of cells, and L is the word length. Space: O(L) — recursion depth. ✨ Key Takeaways: ✅ Strengthened understanding of recursion and backtracking. ✅ Learned to manage visited states effectively in grid problems. ✅ Great exercise in applying DFS to real-world matrix traversal cases. #LeetCode #100DaysOfCode #Java #Backtracking #Recursion #ProblemSolving #DSA #WomenInTech #CodingJourney
To view or add a comment, sign in
-
-
✅Day 51 : Leetcode 1011 - Capacity To Ship Packages within D Days #60DayOfLeetcodeChallenge 🧾 Problem Statement: A conveyor belt has packages that must be shipped from one port to another within a certain number of days. Each package weights[i] represents the weight of a package. We need to find the minimum capacity of the ship so that all packages are shipped within D days. Packages must be loaded in the given order — no reordering allowed. 🧠 My Approach (Binary Search): To find the minimum ship capacity efficiently, I used Binary Search on the capacity range. 1️⃣ The search range is from: low = max(weights) → (heaviest package) high = sum(weights) → (all packages in one go) 2️⃣ Perform binary search between low and high. For each mid-capacity, I used a helper function to calculate how many days it would take to ship all packages with that capacity. 3️⃣ If the total days required ≤ given D, move left (try smaller capacity). Else, move right (increase capacity). ⏱ Time Complexity: O(N * log(sum(weights) - max(weights))) where N = number of packages 💾 Space Complexity: O(1) #LeetCode #DSA #BinarySearch #ProblemSolving #Java #Algorithms #CodingJourney #SoftwareEngineering #TechLearning #DataStructures
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
Keep going