📌 LeetCode Daily Challenge — Day 3 Problem: 1545. Find Kth Bit in Nth Binary String Topic: String, Recursion, Divide and Conquer 🧠 Approach (Simple Thinking): 🔹 Every string Sn is made of 3 parts: The previous string S(n-1) on the left A single "1" sitting right in the middle The flipped and reversed version of S(n-1) on the right 🔹 The string doubles in size every level by S20 you're looking at 1M+ characters. Building it fully? Not a chance. So instead, we recursively figure out which part position k falls into 🔹 If k is in the left half → it behaves exactly like S(n-1). Just recurse with the same k and go one level down 🔹 If k is exactly the middle → no need to recurse at all. The middle is always '1', guaranteed by construction 🔹 If k is in the right half → the right half is a mirror of the left half but with all bits flipped. So we calculate the mirrored position, recurse into the left half to get that bit, and then flip the answer 🔹 Base case → when n = 1, the string is just "0". Return it and start unwinding ⏱️ Time Complexity: Recurse at most n levels deep → O(n) n = the level of the binary string 📦 Space Complexity: Recursive call stack depth is n → O(n) No extra arrays or data structures created 📝 Put together a full walkthrough covering the approach, dry run, and code explanation. 👉 check it out here: https://lnkd.in/gGrReU9W Got a different way to tackle this? Always curious to see alternate approaches share it in the comments below! 🙌 Until the next one, happy coding! 🚀 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
LeetCode Challenge: Find Kth Bit in Nth Binary String
More Relevant Posts
-
🚀 Day 546 of #750DaysOfCode🚀 🔥 Solved: Check if Strings Can be Made Equal With Operations I (LeetCode Easy) 💡 Problem Insight We are allowed to swap characters at indices where: 👉 j - i = 2 This means: Index 0 ↔ 2 (even positions) Index 1 ↔ 3 (odd positions) 🚫 But we cannot mix even and odd indices 🧠 Key Observation The string is divided into 2 independent groups: Even indices → (0, 2) Odd indices → (1, 3) 👉 We can rearrange within each group freely 👉 So both groups must match between s1 and s2 ⚡ Approach Extract characters: Even indices from both strings Odd indices from both strings Sort both groups Compare: Even parts must match Odd parts must match 📈 Complexity Time: O(1) Space: O(1) 💬 Key Takeaway Sometimes problems look like string manipulation, but the real trick is: 👉 Understanding constraints → grouping → independent transformations 🔁 Consistency check ✔️ Another day, another step forward 🚀 #LeetCode #DataStructures #Algorithms #Java #CodingChallenge #ProblemSolving #100DaysOfCode #Consistency
To view or add a comment, sign in
-
-
Day 6 — this problem broke my brain until I thought about it like a chef cutting a sandwich. 🧠 LeetCode 241 — Different Ways to Add Parentheses The problem: Given an expression, return ALL possible results from every different way to place parentheses. 2-1-1 → [0, 2] — same numbers, different brackets, different answers. The insight 💡 Every operator is a potential "last operation." Split there. Solve left. Solve right. Combine every result from both sides. Repeat recursively for every operator. That's it. Divide and Conquer. "2*3-4*5" Split at * → left:"2", right:"3-4*5" Split at - → left:"2*3", right:"4*5" Split at * → left:"2*3-4", right:"5" ... combine all results → [-34,-14,-10,-10,10] Why recursion fits perfectly here: Smaller subexpressions have the same structure as the original. Classic D&C pattern — break, solve, merge. Real world connection 🔗 This is exactly how compilers build Abstract Syntax Trees. Every operator is a split point. Every subexpression becomes a subtree. Day 6 done. Streak alive. 💪 #DSA #LeetCode #Java #DivideAndConquer #Recursion #100DaysOfCode #BackendDeveloper #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 Daily LeetCode Challenge – Day 37 Today’s problem was Find All Possible Stable Binary Arrays I. Problem: We are given three integers zero, one, and limit. We need to count the number of stable binary arrays such that: The array contains exactly zero number of 0s. The array contains exactly one number of 1s. Any subarray with size greater than limit must contain both 0 and 1. In simpler terms, we cannot place more than limit consecutive 0s or 1s, otherwise the array becomes unstable. The brute force that came to mind: Generate all possible arrays using the given number of 0s and 1s and then check if they satisfy the limit condition. But this approach quickly becomes inefficient because the number of combinations grows rapidly. 💡 Better Idea – Dynamic Programming with Memoization First, we focus on the limit. The limit tells us the maximum number of identical elements that can appear consecutively. For example, if limit = 2, then sequences like [0,0,0] or [1,1,1] are not allowed because they contain more than two identical elements in a row, which would make the array unstable. To construct valid arrays, we add elements in blocks: ->If the last placed element was 1, the next block must contain 0s. ->If the last placed element was 0, the next block must contain 1s. ->The size of each block can range from 1 to min(remaining elements, limit). This ensures that: we never exceed the number of remaining 0s or 1s we never violate the limit constraint. We recursively explore all valid possibilities while keeping track of: ->remaining 0s ->remaining 1s ->the last placed element. To avoid recomputation, we store previously computed results in a DP table. ⚡ Time Complexity: O(zero × one × limit) ⚡ Space Complexity: O(zero × one) 🔍 Key Insight: Instead of generating all binary arrays, we construct them step by step while respecting the limit constraint and store intermediate results, which turns an exponential brute force solution into an efficient dynamic programming approach. #LeetCode #DailyCodingChallenge #Java #DynamicProgramming #Algorithms #ProblemSolving #CodingInterview
To view or add a comment, sign in
-
-
🚀 Day 78 / 100 – LeetCode Daily Challenge 🧠 Problem: Triconic Subarray Maximum Sum 📅 Date: March 7, 2026 🏆 Runtime: 3 ms | Beats 99.94% 📦 Memory: 95.28 MB | Beats 46.16% 📝 Problem Insight Today’s challenge was to find the maximum sum of a triconic subarray – a sequence that first decreases, then increases, and finally decreases again. It’s like a "mountain" with two peaks and one valley in between, but in a specific order: down → up → down. This is a more complex variant of the classic mountain or bitonic subarray problems. It requires careful scanning of the array to detect valid triconic patterns and compute their sums efficiently. 💡 My Approach I used a two-pointer expansion method: Iterate through the array and treat each index as a potential peak or valley. Expand left and right while the pattern matches the triconic property. Keep track of the maximum sum encountered. Although the code snippet is incomplete here, the full solution involves: Precomputing left and right decreasing/increasing trends. Validating the three-phase pattern for each possible center. Avoiding redundant computations to keep the time complexity close to O(n). 📊 Results ✅ 861 / 861 test cases passed ⚡ Runtime: 3 ms (beats 99.94% of Java submissions) 📈 Memory: 95.28 MB (beats 46.16%) 🧠 Key Takeaway Pattern recognition problems like this one are great for sharpening your array traversal logic and understanding how to break down complex patterns into manageable checks. The challenge is not just in finding the sum, but in ensuring the pattern holds throughout. 🔗 Let’s Connect! I’m documenting my #100DaysOfCode journey every day – follow along for more problem-solving insights, optimizations, and LeetCode grind! 💻⚡ #LeetCode #Java #CodingChallenge #100DaysOfCode #Day78 #TriconicArray #ProblemSolving #TechJourney #SoftwareEngineering #Algorithms #DataStructures #CodeNewbie #DevCommunity #Programming
To view or add a comment, sign in
-
-
🚀 Day 10 – LeetCode Practice Today, I solved the Trapping Rain Water problem on LeetCode: 🎯 Difficulty: Hard 💻 Language Used: Java 💡 Approach: • Given an elevation map represented by an array, the task was to determine how much rainwater can be trapped after raining. • I used a two-pointer technique with left & right pointers moving inward: – Tracked max height from both ends (leftMax, rightMax). – At each step, water trapped is based on the smaller max height minus current height. – Moving pointers inward ensures efficient calculation in one pass. ⏱ Complexity: • Time Complexity: O(n) • Space Complexity: O(1) 📚 Key Takeaway: This problem reinforced how two-pointer strategies can optimize otherwise naïve solutions and how keeping track of boundary conditions leads to efficient space-constant algorithms. Consistent problem-solving practice continues to strengthen my algorithmic intuition and implementation skills. 💪 #LeetCode #Java #DSA #TwoPointers #Algorithms #ProblemSolving #CodingPractice #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 4 Problem: 1582. Special Positions in a Binary Matrix Topic: Array, Matrix 🧠 Approach (Simple Thinking): 🔹 A position is special only if it holds a 1 that is alone in its entire row AND its entire column 🔹 Checking row and column for every cell separately is slow and repetitive 🔹 So we pre-compute rowSum and colSum in one pass before making any decisions 🔹 rowSum[i] == 1 means no other 1 exists in that row 🔹 colSum[j] == 1 means no other 1 exists in that column 🔹 If mat[i][j] == 1 and both sums equal 1 — that's your special position 🔹 Preprocessing once and reusing is the real trick here ⏱️ Time Complexity: Two passes through the full matrix → O(m × n) Every cell is visited exactly twice, nothing more 📦 Space Complexity: Two small arrays for row and column sums → O(m + n) No recursion, no extra grid, just two lightweight arrays doing all the work I wrote a full breakdown with dry run, analogy and step by step code walkthrough here: https://lnkd.in/gFgQxQRP If you approached this differently or have a cleaner way to think about it, drop it in the comments — always curious to see different perspectives 💬 See you in the next problem 👋 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
To view or add a comment, sign in
-
-
Day 18 of #75DaysOfLeetCode 🚴♂️ LeetCode Problem Solved: Find the Highest Altitude (1732) Today I solved “Find the Highest Altitude” on LeetCode. This problem focuses on understanding prefix sum logic and cumulative calculations. 🔹 Problem Summary: A biker starts a road trip at altitude 0. We are given an array gain, where each value represents the net change in altitude between consecutive points. The goal is to determine the highest altitude reached during the trip. 🔹 Key Idea: Start with altitude 0, keep adding the gains step by step, and track the maximum altitude reached during the journey. 💻 Java Solution: class Solution { public int largestAltitude(int[] gain) { int currentAltitude = 0; int maxAltitude = 0; for (int g : gain) { currentAltitude += g; maxAltitude = Math.max(maxAltitude, currentAltitude); } return maxAltitude; } } 📌 Concepts Used: • Prefix Sum • Array Traversal • Basic Simulation ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Consistently practicing problems like these helps strengthen problem-solving and algorithmic thinking. #LeetCode #Java #DataStructures #Algorithms #ProblemSolving #CodingJourney #Programming
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 14 Problem: 1415. The k-th Lexicographical String of All Happy Strings of Length n Topic: Backtracking, String 📌 Quick Problem Sense: A happy string uses only ['a', 'b', 'c'] and no two adjacent characters are the same. Given n (length) and k (position), return the k-th happy string in lexicographical order — or "" if fewer than k exist. You need to generate candidates in order and stop at the k-th one. Backtracking is your entire strategy! 🧠 Approach (Simple Thinking): 🔹 At each position you have at most 2 choices — any character from ['a','b','c'] except the previous one 🔹 Characters are tried in alphabetical order — this naturally gives lexicographic ordering 🔹 Use backtracking to build strings character by character, skipping invalid choices 🔹 Every time a string of length n is completed, increment a counter 🔹 When counter hits k, that's your answer — return immediately, no need to explore further 🔹 If backtracking exhausts all possibilities and counter never reached k, return "" 🔹 Total happy strings = 3 * 2^(n-1) → if k exceeds this, return "" instantly ⏱️ Time Complexity: Each position has at most 2 choices, depth is n → O(2^n) We stop early at the k-th string, so often much faster in practice 📦 Space Complexity: Recursion stack depth = n, current string buffer = n → O(n) No extra arrays storing all strings! I wrote a full breakdown with dry run, analogy, and step-by-step code walkthrough here: https://lnkd.in/gFrtgPFf If you solved it iteratively or used a math trick to directly compute the k-th string without generating all of them, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #Backtracking #CodingInterview #Java
To view or add a comment, sign in
-
-
🚀 Day 25 of my #100DaysOfCode Journey Today, I solved the LeetCode problem Valid Perfect Square. Problem Insight: Given a positive integer, the task is to determine whether it is a perfect square without using built-in functions like sqrt(). Approach: Used Binary Search to efficiently find whether a number has an integer square root. Initialized search range from 0 to num Calculated mid and checked mid * mid If equal → return true If square is smaller → move right (low = mid + 1) If square is larger → move left (high = mid - 1) Used long for multiplication to avoid overflow issues. Time Complexity: O(log n) — efficient binary search approach Takeaway: Binary Search is not just for arrays — it can be applied to mathematical problems to optimize performance and avoid brute force. #DSA #Java #LeetCode #CodingJourney #100DaysOfCode #BinarySearch
To view or add a comment, sign in
-
-
🚀 Day 10 – LeetCode Practice Today, I solved the First Missing Positive problem on LeetCode: 🎯 Difficulty: Hard 💻 Language Used: Java 💡 Approach: • Given an unsorted integer array, the task was to find the smallest missing positive integer in O(n) time and O(1) extra space. • I used an index hashing technique by placing each positive number n at index n–1. • After rearranging in-place, the first position where the value doesn’t match the index+1 is the answer. • If all positions are correct, the missing positive is length + 1. ⏱ Complexity: • Time Complexity: O(n) • Space Complexity: O(1) 📚 Key Takeaway: This problem reinforced how careful in-place rearrangement + index mapping can eliminate the need for extra data structures while achieving linear time — a powerful pattern for optimized solutions. Consistent problem-solving practice continues to strengthen my algorithmic intuition and implementation skills. 💪 #LeetCode #Java #DSA #Arrays #IndexHashing #ProblemSolving #Algorithms #CodingPractice #100DaysOfCode #SoftwareDeveloper
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