📌 Day 8/100 - Search Insert Position (LeetCode 35) 🔹 Problem: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be inserted in order. 🔹 Approach: I used a binary search approach for efficiency 🔍 1️⃣ Start with two pointers — low and high. 2️⃣ Find the mid index and compare nums[mid] with the target. 3️⃣ If target equals nums[mid], return mid. 4️⃣ If target is smaller, move the high pointer left. 5️⃣ If target is greater, move the low pointer right. 6️⃣ When the loop ends, low gives the correct insert position. 🔹 Key Learning: Binary Search saves time — reducing O(n) to O(log n)! Understanding the condition when to move left/right is key. Even simple problems sharpen logical precision and boundary handling. Each problem strengthens the logic muscle 🧠 — one step closer to mastering algorithms! 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
"Day 8/100: Solving Search Insert Position with Binary Search"
More Relevant Posts
-
🗓 Day 8/ 100 – #100DaysOfLeetCode 📌 Problem 3234: Count the Number of Substrings With Dominant Ones A substring is said to have dominant ones if: 👉 #1s ≥ (#0s)² The task is to count how many substrings in the binary string satisfy this condition. 🧠 My Approach: 🔹 Iterated through substrings while maintaining counts of zeros and ones. 🔹 Used the condition ones ≥ zeros² to determine whether a substring is valid. 🔹 Applied early stopping when the zero count became too large, since the quadratic requirement makes dominance increasingly difficult to achieve. 🔹 This pruning significantly reduced unnecessary checks and improved the overall efficiency. ⏱ Time & Space Complexity Time Complexity: O(n · √n) Because for each starting index, we only explore substrings until the zero count reaches ~√n (beyond which zeros² becomes too large to satisfy). This is a major improvement over the brute-force O(n²). Space Complexity: O(1) Only uses a few counters (ones, zeros, indices). 💡 Key Learning: This problem beautifully shows how mathematical constraints can simplify substring evaluation. Recognizing that zeros affect the condition quadratically helped guide a smarter pruning strategy, turning an expensive brute-force check into something efficient and elegant. #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #654 — Maximum Binary Tree 📘 Problem: Given an integer array without duplicates, the task is to build a maximum binary tree. The construction rules are: 1️⃣ The root is the maximum element in the array. 2️⃣ The left subtree is built recursively from elements to the left of the maximum. 3️⃣ The right subtree is built recursively from elements to the right of the maximum. Example: Input → [3,2,1,6,0,5] Output → [6,3,5,null,2,0,null,null,1] 🧠 My Approach: I solved this problem using a recursive divide-and-conquer approach. 1️⃣ Find the index of the maximum element in the given range — this becomes the root. 2️⃣ Recursively build the left subtree from the subarray before the maximum element. 3️⃣ Recursively build the right subtree from the subarray after the maximum element. 💡 What I Learned: ✅ How recursion naturally fits into tree construction problems ✅ The concept of divide and conquer applied to array-based tree building ✅ How to translate problem definitions into direct recursive structure #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
🚀 Day 416 of #500DaysOfCode Problem: 1513. Number of Substrings With Only 1s Platform: LeetCode – Medium Today’s challenge was a classic binary-string problem that focuses on counting substrings composed only of '1' characters. Sounds simple—but with constraints up to 100,000 characters, brute force is impossible. 🔍 What I Learned The key insight is: Whenever you find a continuous streak of 1s of length k, it contributes: k⋅(k+1)2\frac{k \cdot (k+1)}{2}2k⋅(k+1)substrings made only of 1s. Example: 111 → • "1" (3 times) • "11" (2 times) • "111" (1 time) Total = 6 So instead of checking all substrings, we just: ➡️ Count lengths of 1-streaks ➡️ Use the formula ➡️ Keep sum modulo 1e9+7 🧠 Why This Problem Is Useful Builds intuition for pattern-counting in strings Reinforces how mathematical optimization replaces brute-force loops Helps in understanding frequency-based substring logic 📌 Output Examples Input: "0110111" → Output: 9 Input: "101" → Output: 2 Input: "111111" → Output: 21 💡 Reflection Simple logic + clever math = powerful optimization. This problem reminded me how often the pattern matters more than the individual characters. #500DaysOfCode #Day416 #LeetCode #Java #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
-
-
💡 LeetCode 2859 – Sum of Values at Indices With K Set Bits 💡 Today, I solved LeetCode Problem #2859, a clever mix of bit manipulation and array traversal that emphasizes how understanding binary representations can simplify computational logic. ⚙️ 🧩 Problem Overview: You are given a list of integers nums and an integer k. Your task is to find the sum of all elements at indices whose binary representation contains exactly k set bits (1s). 👉 Examples: Input → nums = [5,10,1,5,2], k = 1 → Output → 13 (Indices 1 and 2 have one set bit → nums[1] + nums[2] = 10 + 3) 💡 Approach: 1️⃣ Loop through all indices in the list. 2️⃣ Use Integer.bitCount(i) to count the number of set bits in the binary representation of each index. 3️⃣ If it equals k, add nums[i] to the sum. 4️⃣ Return the final total. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Linear scan of the list. ✅ Space Complexity: O(1) — Constant space usage. ✨ Key Takeaways: Strengthened understanding of bit-level operations using Java’s built-in methods. Reinforced how binary logic often leads to elegant and concise solutions. Demonstrated the power of combining mathematical reasoning with simple iteration. 🌱 Reflection: Bit manipulation is one of the most underrated yet powerful tools in problem-solving. This problem shows how thinking in binary can make complex conditions crystal clear — and the solution clean, efficient, and elegant. 🚀 #LeetCode #2859 #Java #BitManipulation #DSA #ProblemSolving #CodingJourney #AlgorithmicThinking #CleanCode #DailyPractice #ConsistencyIsKey
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
-
-
🗓️ Day 32 / 100 – Binary Tree Maximum Path Sum 🌳💻 Today’s challenge pushed my recursion and problem-solving skills to the limit. I worked on finding the Maximum Path Sum in a Binary Tree — a classic yet tricky problem that tests your understanding of recursion, global state management, and tree traversal. 🔁 It took me 10 submissions to finally get it right! Each attempt helped me uncover a new insight — from handling negative values to understanding how and where to update the global maximum. 💡 The major improvement came on the 11th attempt, when I replaced the static global variable with a local reference (int[] maxSum). This small design change made my code cleaner, reusable, and thread-safe — a great reminder that writing correct code is one thing, but writing robust code is another. 📈 Key Learnings: Manage global state carefully in recursive problems. Use reference wrappers (like int[] or small helper classes) to avoid side effects. Debugging recursion is easier when you visualize each return value and what it represents. 🧠 Code snippet (improved version): public int maxPathSum(TreeNode root) { int[] maxSum = {Integer.MIN_VALUE}; maxPath(root, maxSum); return maxSum[0]; } 🚀 Reflection: Persistence pays off! Every failed attempt was just one step closer to understanding the problem deeply. #100DaysOfCode #Day32 #Java #DSA #LeetCode #CodingJourney #LearningInPublic #ProblemSolving #BinaryTree
To view or add a comment, sign in
-
-
🚀 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
-
-
✅ Day 68 of LeetCode Medium/Hard Edition Today’s challenge was “Number of Ways to Form a Target String Given a Dictionary” — a brilliant Dynamic Programming and Combinatorics problem that tests precision in transitions and precomputation logic 🧩⚙️ 📦 Problem: You’re given an array of equal-length strings words and a target string target. You must form target from left to right by picking characters from the columns of words under these rules: 1️⃣ Once you use column k from any word, all columns ≤ k in every word become unusable. 2️⃣ You can use multiple characters from the same word, respecting column progression. Return the number of ways to form target modulo 1e9 + 7. 🔗 Problem Link: https://lnkd.in/gns9CwWa ✅ My Submission: https://lnkd.in/g7bsgZq9 💡 Thought Process: This problem is a clever mix of frequency compression and DP memoization. We precompute a frequency table freq[26][m], where each cell represents how many words contain a given letter at column m. Then, using recursion with memoization: 🎯 At each step (i, j) Either use freq[target[i]][j] if it exists → multiply by ways for the next position (i+1, j+1) Or skip the current column → move to (i, j+1) The recurrence relation: dp[i][j] = freq[target[i]][j] * dp[i+1][j+1] + dp[i][j+1] All computations are done modulo 1e9 + 7. ⚙️ Complexity: ⏱ Time: O(26 * n + t * m) — efficient due to frequency precomputation 💾 Space: O(t * m) — for memoized DP table 💭 Takeaway: This challenge reinforced how precomputation and state optimization can transform a seemingly exponential recursion into an elegant polynomial-time solution 🚀 #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #Combinatorics #ProblemSolving #Java #CodingChallenge #DSA
To view or add a comment, sign in
-
Explore related topics
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