🚀 Solved LeetCode 338: Counting Bits 🚀 I recently worked on the Counting Bits problem, where the task is: 👉 Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 🔹 My Approach: Initialize an array of size n+1. For each number from 1 to n: Copy the number into a temporary variable. Use a loop to repeatedly divide by 2, counting the remainder (num % 2) each time. Store the total count of 1’s in the array. Return the final array. 📊 Complexity Analysis: Time Complexity: O(n log n) Each number requires about log(i) steps to process its binary digits. Space Complexity: O(n) Only the result array of size n+1 is used. ✨ Key Learning: This problem strengthened my understanding of binary representation and iterative problem solving. It was a great reminder that even simple bitwise operations can unlock powerful solutions. #LeetCode #Java #ProblemSolving #BackendDevelopment #CodingJourney #BitManipulation
Counting Bits in Binary Representation
More Relevant Posts
-
🚀 Day 19 of My LeetCode Challenge Today’s problem: Find All Duplicates in an Array (LeetCode 442) 🔍 Problem Summary: Given an array of integers where each value appears once or twice and lies between 1 and n, return all elements that appear twice. 🧠 Key Insight: Since numbers are in the range 1 to n, we can use the array itself to track visited elements by marking indices negative. ⚙ Approach (O(n) time | O(1) space): ✔ Traverse the array ✔ Use value → index mapping ✔ If index already negative → duplicate found ⏱ Complexity: ✅ Time: O(n) ✅ Space: O(1) 📌 What I Learned Today: Using index mapping for in-place marking How constraints help optimize space Recognizing patterns for array-based hashing #Day19 #LeetCode #Java #DSA #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
#Day32 of #365DaysOfCode Today’s LeetCode Practice: 🔹 Container With Most Water (LeetCode 11) Solved a classic two-pointer optimization problem where the goal is to find two lines that together form a container holding the maximum water. 💡 Key Insight: Start with two pointers at both ends. Calculate area using: width × min(height[left], height[right]) Move the pointer with the smaller height inward, because the smaller height limits the water capacity. This guarantees exploring better possibilities efficiently. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Consistency > Motivation. Day by day, improving problem-solving and logical thinking skills #LeetCode #ProblemSolving #Java #CodingJourney #FutureEngineer #Consistency #LearningEveryday
To view or add a comment, sign in
-
-
Day 9/100 – LeetCode Challenge Problem Solved: Pow(x, n) Today I worked on implementing a power function that calculates x raised to the power n. The challenge lies in handling edge cases such as negative exponents and integer overflow scenarios, especially when n equals Integer.MIN_VALUE. The core idea was to carefully manage the exponent: If n is negative, convert the base to its reciprocal. Convert the exponent to a positive value for computation. Handle extreme integer boundaries safely. The straightforward implementation multiplies the base repeatedly, but this approach runs in linear time with respect to n. While it works for smaller inputs, it highlights an important lesson about optimization and algorithmic efficiency. Time Complexity: O(n) Space Complexity: O(1) #100DaysOfLeetCode #Java #ProblemSolving #Algorithms #Consistency #Learning
To view or add a comment, sign in
-
-
🚀 Day 512 of #750DaysOfCode 🚀 🔢 868. Binary Gap (LeetCode – Easy) Today’s problem was a clean bit manipulation exercise. 🧠 Problem Summary Given a positive integer n, return the longest distance between two adjacent 1s in its binary representation. 📌 Distance = difference between their bit positions. Example: n = 22 Binary = 10110 Distances: First pair → distance = 2 Second pair → distance = 1 ✅ Answer = 2 💡 Key Idea We don’t need to convert to string. Instead: Traverse bits using right shift (n >> 1) Track the last position where we saw 1 Update maximum distance whenever we see another 1 🔥 What I Practiced Bitwise AND (n & 1) Right shift (n >> 1) Tracking bit positions Efficient binary traversal without converting to string 🎯 Time Complexity O(log n) Because we process each bit once. 🧠 Takeaway Even simple bit problems strengthen: Logical thinking Position tracking Understanding binary deeply Bit manipulation problems look small — but they build serious foundation. #750DaysOfCode #Day512 #LeetCode #Java #BitManipulation #Binary #ProblemSolving
To view or add a comment, sign in
-
-
#Day28 of #365DaysOfCode Today’s LeetCode practice: 🔹 Word Search (LeetCode 79) Solved a backtracking problem where I had to check whether a given word exists in a 2D board by moving horizontally or vertically through adjacent cells. 💡 Key Insight: Start exploring from every cell. If the character matches the current letter of the word, move in all 4 possible directions. Mark the cell as visited and revert the change if the path doesn’t lead to a solution. On to Day 29 🔥 #LeetCode #Java #DSA #ProblemSolving #CodingJourney #Backtracking #Recursion
To view or add a comment, sign in
-
-
Day 57 - LeetCode Journey Solved LeetCode 2104: Sum of Subarray Ranges (Medium) today using a brute force + optimization approach. This journey isn’t about solving the hardest problems daily, but about showing up consistently and improving step by step. Problems like this help in building a deeper understanding of arrays and how subarrays behave. Today’s problem reinforced key concepts like: • Understanding how to generate all subarrays efficiently • Tracking minimum and maximum values dynamically • Avoiding recomputation using smart updates • Writing clean and logical nested loop solutions The idea is simple — for each starting index, expand the subarray and keep updating min and max to calculate the range 💡 Every problem adds a new layer to problem-solving skills, and that’s where real growth happens 💯 ✅ Better understanding of subarrays and ranges ✅ Improved thinking for optimization ✅ More confidence in array-based problems Still a long way to go, but progress is progress 🚀 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #Algorithms #Programming #DeveloperJourney #KeepCoding
To view or add a comment, sign in
-
-
Day 17 – LeetCode 1004 | Sliding Window Done Right (O(n) Solution) Day 17 of solving problems consistently. Solved LeetCode 1004 – Max Consecutive Ones III. Problem: Given a binary array, you can flip at most k zeros. Return the maximum number of consecutive 1s possible. Brute force checks every subarray → O(n²) → wasteful. A better approach is Sliding Window + Two Pointers → O(n). Core logic: • Expand window with right pointer • Count zeros • If zeros exceed k → move left pointer • Track max window length This problem is a good reminder that: Constraints usually hint the optimal technique. If you see “subarray + max/min + linear time” → think Sliding Window first. Consistency builds skill. 17 days. No breaks. Code + explanation in the video 👇 #LeetCode #DSA #Algorithms #SlidingWindow #TwoPointers #Java #ProblemSolving #CodingInterview #SoftwareDeveloper #100DaysOfCode #TechJourney
To view or add a comment, sign in
-
#100DaysOfCode 🚀 👉Solved: LeetCode #16 – 3Sum Closest After solving the classic 3Sum problem earlier, this variation pushed me to think slightly differently. Instead of finding an exact triplet sum equal to 0, this time the goal was to find the sum *closest* to a given target. 🔹 Approach: • Sorted the array • Fixed one element at a time • Applied the Two Pointer technique • Continuously tracked the minimum absolute difference Key Insight: Sometimes optimization problems are not about exact matches, but about minimizing deviation. Time Complexity: O(n²) Space Complexity: O(1) This problem strengthened my understanding of: ✔ Two Pointers ✔ Greedy comparison logic ✔ Edge case handling What I learned: Small variations in problem statements can completely change the thinking approach. Classic 3Sum focuses on exact zero. 3Sum Closest focuses on minimizing |sum - target|. #LearnInPublic #DSA #Java #LeetCode #TwoPointers #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 89 of #100DaysOfCode | LeetCode Daily Solved LeetCode Problem #190 – Reverse Bits 🔄💻✅ A classic bit-manipulation problem that really sharpens understanding of how numbers are represented at the binary level. Clean logic, constant time, and pure fundamentals. Key Takeaways: -> Working with bitwise operators (&, <<, >>>) -> Reversing bits by extracting LSB and placing it at the correct position -> Understanding 32-bit integer representation -> Efficient O(1) solution with no extra space Language: Java -> Runtime: 1 ms (Beats 60.34%) -> Memory: 42.61 MB Mastering the basics makes advanced problems feel lighter. Still showing up. Still learning. 🔥💻 #LeetCode #Java #BitManipulation #ReverseBits #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Solved LeetCode #136 — Single Number Today I practiced a clean array-logic problem. 🧩 Problem: In an array, every number appears twice except one. We need to find that single number. 💡 My Approach (Sorting + Pair Checking) • First sort the array so duplicates come together • Then check elements in pairs • The element without a pair is the answer Example: [4,1,2,1,2] → [1,1,2,2,4] → Output = 4 🧠 Key Learning: After sorting, every number stands with its partner — the lonely element reveals itself automatically. Consistent practice is helping me understand patterns, not just memorize solutions. #LeetCode #DSA #ProblemSolving #Arrays #Java #CodingJourney #LearningInPublic
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