#100DaysOfLeetcode journey 🚀 Day 20/100 — Bit Manipulation & Modular Arithmetic! Today’s Problem: 1680. Concatenation of Consecutive Binary Numbers 🔹 The Goal: Given an integer $n$, concatenate the binary representations of numbers from $1$ to $n$ into a single string and return its decimal value modulo $10^9 + 7$. 🔹 The Insight: At first glance, this looks like a string problem, but building a massive binary string is a recipe for a Memory Limit Exceeded (MLE) error. The trick is to realize that when you "append" a new number $i$ to your current result, you are essentially shifting your current value to the left by the number of bits in $i$ and then adding $i$. 🔹 The Difficulty: The numbers grow exponentially. To keep things under control, we apply the property of modular arithmetic: $$(A + B) \pmod M = ((A \pmod M) + (B \pmod M)) \pmod M$$ The real challenge? Knowing when the "bit length" of your current number increases (e.g., when moving from 3 to 4, you go from 2 bits to 3 bits). ✨ Achievement: Successfully bypassed string manipulation entirely to create a pure mathematical $O(n)$ solution. 🔍 Steps followed: ✔ Bit-Width Tracking: Monitored when $i$ reached a power of 2 to increment the shift amount. ✔ Efficient Shifting: Used (ans << bitLength) | i to concatenate values at the bit level. ✔ Modular Discipline: Applied the modulo at every step to prevent integer overflow. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ Thirteen days in and the "bit-shifting" logic is starting to feel like second nature. Onward! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #BitManipulation #MathAlgorithms #SoftwareEngineer #Optimization
Bit Manipulation & Modular Arithmetic Challenge
More Relevant Posts
-
Day 15/100 – LeetCode Challenge Problem Solved: Rotate Image Today’s problem involved rotating an n × n matrix by 90 degrees clockwise without using additional space. The challenge is performing the transformation directly on the existing matrix. The key idea behind the solution is breaking the rotation into two simpler operations. First, transpose the matrix by swapping elements across the main diagonal. This converts rows into columns. After the transpose, reverse each row of the matrix. Together, these two steps effectively rotate the matrix by 90 degrees clockwise. This approach avoids creating a new matrix and performs all operations in-place, which satisfies the constraint of constant extra space. Time Complexity: O(n²) Space Complexity: O(1) Performance: Runtime 0 ms Key takeaway: Complex matrix transformations often become easier when decomposed into simpler operations like transpose and reversal. Day 15 completed. Staying consistent and continuing to strengthen problem-solving skills. #100DaysOfLeetCode #Java #Algorithms #Matrix #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
#100DaysOfCode 🚀 👉Solved: LeetCode 75 – Sort Colors The goal was to sort an array containing only three values: 0 (Red), 1 (White), and 2 (Blue) At first glance this looks like a simple sorting problem. But the twist: ❌ No built-in sort ✔ One pass ✔ Constant space The solution uses the famous **Dutch National Flag Algorithm**. Instead of sorting normally, we maintain three pointers: • low → for 0s • mid → current element • high → for 2s Rules: • If nums[mid] == 0 → swap with low • If nums[mid] == 1 → move mid forward • If nums[mid] == 2 → swap with high This allows sorting the array in a single pass. 📌 Key Points: ✔ In-place sorting ✔ One pass algorithm ✔ Constant space usage ✔ Classic three-pointer technique ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this show how powerful pointer techniques can be. Day 15✅ #DSA #Java #LeetCode #Algorithms #ProblemSolving #100DaysOfCode #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Day 5/100 – LeetCode Challenge Problem: Word Search Today’s challenge was a classic 2D Matrix + DFS + Backtracking problem. Problem Summary: Given a 2D board of characters and a word, determine if the word exists in the grid. Rules: Adjacent cells = horizontal or vertical A cell cannot be reused in the same path Approach Used: Traverse every cell as a starting point Apply Depth First Search (DFS) Mark visited cells temporarily Backtrack after exploring all 4 directions Core idea: Base case → If index == word.length() → return true Boundary check + character match validation Mark visited → Explore → Restore (Backtracking) Key Concepts Practiced: Recursion Backtracking 2D matrix traversal State modification & restoration Time Complexity: O(m × n × 4^L) (L = length of word) This problem reinforced an important lesson: Backtracking is about exploring possibilities and undoing choices efficiently. #100DaysOfCode #LeetCode #DSA #Java #Backtracking #SoftwareEngineerJourney #CodingInterview
To view or add a comment, sign in
-
-
🚀 Day 24 of My LeetCode Consistency Streak Today I solved the problem **“Complement of Base 10 Integer”** on LeetCode. This problem focuses on **Bit Manipulation**, where the goal is to flip all bits in the binary representation of a number and return the resulting value in base-10. For example, the integer 5 is `101` in binary and its complement becomes `010`, which equals 2. :contentReference[oaicite:0]{index=0} 💡 Key Idea: Instead of flipping bits manually, we can create a **bitmask with all 1s up to the most significant bit of the number** and use the XOR operation to flip the bits efficiently. ⚙️ Approach: • Count the number of bits required to represent the number • Create a mask like `(1 << bits) - 1` (which gives all 1s) • XOR the mask with the original number to get the complement • Handle the edge case when `n = 0` ⏱ Complexity: Time Complexity: **O(log n)** Space Complexity: **O(1)** Problems like this are a great reminder of how powerful **bitwise operations** can be when solving algorithmic problems efficiently. 🔗 Problem Link: https://lnkd.in/dfUMMYFu 🔗 My Solution: https://lnkd.in/ddDY2y26 Consistency > Motivation. 24 days down, many more to go. 💪 #LeetCode #DSA #BitManipulation #CodingJourney #ProblemSolving #Java #Consistency #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 15 of my #30DayCodeChallenge: Swapping Nodes in Pairs! The Problem: Swap Nodes in Pairs. Given a linked list, the goal is to swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (only nodes themselves may be changed). The Logic: This problem is a classic exercise in Pointer Manipulation and maintaining structural integrity in a Linked List: 1. Dummy Node Strategy: I initialized a dummy node pointing to the head. This acts as a fixed anchor, ensuring I can easily return the new head of the list even after the original head has been swapped. 2. The Three-Pointer Dance: To swap two nodes (cur and t), I need ✓ nage three specific connections for every pair: **-Point the previous node (pre) to the second node of the pair (t). **- Point the first node (cur) to the node following the pair (t. next). **- Point the second node (t) back to the first node (cur). 3. Iterative Traversal: The loop continues as long as there is a full pair remaining (cur ! = nul1 && cur.next ! = null). After each swap, the pre and cur pointers shift forward to prepare for the next pair. Another step closer to mastery. Onward to Day 16! #Java #Algorithms #DataStructures #LinkedList #ProblemSolving #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🌱 Day 11 of my #100DaysOfCode Journey Today I solved LeetCode Problem – Contains Duplicate. The problem asks us to determine if an integer array contains any duplicate values. If any value appears more than once, we return true; otherwise, false. The approach I used today was to sort the array first and then check adjacent elements for equality. This helps detect duplicates efficiently in a single pass. 🔹 What I practiced today: ✅ Array manipulation and sorting ✅ Comparing adjacent elements to find duplicates ✅ Thinking about time vs. space trade-offs 📊 Complexity Analysis: • Time Complexity: O(n log n) — due to sorting • Space Complexity: O(1) — in-place array check A simple yet practical problem that strengthens array handling and logical thinking in algorithm problems. #LeetCode #Java #DSA #100DaysOfCode #CodingJourney #ContainsDuplicate
To view or add a comment, sign in
-
-
🚀 Day 44 of #100DaysOfCode Solved 1011. Capacity To Ship Packages Within D Days on LeetCode 📦 🧠 Key Insight: We need to find the minimum ship capacity such that all packages can be shipped within D days. This is a classic case of Binary Search on Answer. ⚙️ Approach: 1️⃣ The minimum capacity = max(weight) (since one package must fit) 2️⃣ The maximum capacity = sum of all weights 3️⃣ Apply Binary Search between these bounds 4️⃣ For each capacity mid, simulate shipping: 🔹Keep adding weights until capacity exceeds 🔹Move to the next day when exceeded 5️⃣ If we can ship within D days → try smaller capacity 6️⃣ Else → increase capacity This helps us find the minimum valid capacity efficiently. ⏱️ Time Complexity: O(n log(sum)) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #Algorithms #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Solved: Product of Array Except Self (LeetCode 238) Today I solved a very interesting problem that strengthens array + prefix-suffix concepts. 🔹 Problem: Given an array, return a new array where each element is the product of all elements except itself — without using division and in O(n) time. 🔹 Approach: Instead of brute force, I used an optimized approach: ✅ Prefix Product (Left side) ✅ Suffix Product (Right side) This avoids division and keeps space & time efficient. 🔹 Key Idea: First pass: store product of all elements to the left Second pass: multiply with product of all elements to the right 🔹 Code Insight: Efficient use of a single array + running suffix variable 🔹 Complexity:🚀 Solved: Product of Array Except Self (LeetCode 238) Today, I tackled an interesting problem that enhances understanding of array concepts, particularly prefix and suffix approaches. 🔹 **Problem:** Given an array, the task is to return a new array where each element is the product of all other elements, excluding itself—without using division and ensuring an O(n) time complexity. 🔹 **Approach:** Instead of using a brute-force method, I opted for an optimized solution: ✅ Compute a Prefix Product (for the left side) ✅ Compute a Suffix Product (for the right side) This method avoids division while maintaining efficiency in both time and space. 🔹 **Key Idea:** - **First pass:** Store the product of all elements to the left of each element. - **Second pass:** Multiply these results by the product of all elements to the right of each element. 🔹 **Code Insight:** Utilizing a single array along with a running suffix variable enhances efficiency. 🔹 **Complexity:** - Time: O(n) - Space: O(1) (excluding the output array) 💡 This problem deepened my understanding of how prefix and suffix patterns can significantly optimize brute-force solutions. #DSA #LeetCode #Java #CodingJourney #100DaysOfCode #ProblemSolving #TechLearning🚀 Solved: Product of Array Except Self
To view or add a comment, sign in
-
-
🚀 Day 11 – #50DaysLeetCodeChallenge Today I solved the 3Sum problem. 📌 Problem Statement Given an integer array nums, return all the unique triplets [nums[i], nums[j], nums[k]] such that: i ≠ j ≠ k nums[i] + nums[j] + nums[k] = 0 ⚠️ The solution must not contain duplicate triplets. Example: Input: [-1,0,1,2,-1,-4] Output: [[-1,-1,2], [-1,0,1]] 💡 Approach I Used – Sorting + Two Pointers 1️⃣ Sort the array 2️⃣ Fix one element i 3️⃣ Use two pointers: left = i + 1 right = end of array 4️⃣ Check the sum: If sum == 0 → add triplet If sum < 0 → move left++ If sum > 0 → move right-- 5️⃣ Skip duplicates to avoid repeated triplets ⚙️ Key Idea Reduce the problem from 3Sum → 2Sum (using two pointers) Sorting helps in efficient traversal and duplicate handling 🧠 What I learned today ✔️ How sorting simplifies complex problems ✔️ Converting problems into smaller subproblems (3Sum → 2Sum) ✔️ Handling duplicates carefully From simple arrays → advanced pointer techniques 🚀 Consistency is making a difference! #LeetCode #Java #DSA #CodingChallenge #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
LeetCode 493 — Reverse Pairs Worked on the Reverse Pairs problem today. The task is to count pairs (i, j) such that: • i < j • nums[i] > 2 × nums[j] A brute force solution would check every pair, which results in O(n²) time complexity and becomes inefficient for larger inputs. Approach used :- Instead of checking all pairs directly, I used a modified Merge Sort approach. The idea is: - split the array recursively (similar to merge sort) - both halves become sorted - before merging them, count pairs that satisfy the reverse pair condition - then perform the normal merge step Because both halves are sorted, it becomes possible to count multiple valid pairs efficiently during traversal. Things that became clear: - the problem is closely related to the inversion count pattern - sorting the halves helps reduce unnecessary comparisons - the counting step must happen before merging - overall time complexity improves to O(n log n) Finally got the solution accepted. #leetcode #dsa #algorithms #mergesort #problemSolving #java #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