🚀 LeetCode POTD — 1513. Number of Substrings With Only 1s 🎯 Difficulty: Medium | Topics: Counting, Math, Sliding Window 🔗 Solution Link: https://lnkd.in/gw_b_eXH Today’s #LeetCode Problem of the Day was a straightforward counting problem — all about finding how many substrings contain only '1' in a binary string. My approach was simple yet efficient: Traverse the string and count consecutive sequences of 1s. For any streak of length n, the number of valid substrings is: n⋅(n+1)2\frac{n \cdot (n + 1)}{2}2n⋅(n+1) After collecting a streak, jump the index forward by count - 1 (since all those characters are already processed). This keeps the solution clean and avoids unnecessary nested checks. 📈 Complexity: Time: O(n) Space: O(1) 💡 Takeaway: Problems like this remind us how far simple math can take you — a clean formula can replace dozens of lines of brute-force logic. #LeetCode #ProblemOfTheDay #Math #StringProcessing #Counting #DSA #CodingChallenge #SoftwareEngineering #CodingJourney #100DaysOfCode #LearningInPublic #TechCommunity
LeetCode POTD: Counting Substrings With Only 1s
More Relevant Posts
-
🚀 DSA Progress – Day 110 ✅ Problem #392: Is Subsequence 🧠 Difficulty: Easy | Topics: Two Pointers, String, Greedy 🔍 Approach: Implemented a Two-Pointer approach to determine if one string (s) is a subsequence of another (t). Step 1 (Initialization): Start two pointers — i for string s and j for string t. Step 2 (Traversal): Traverse through both strings: If s[i] == t[j], move both pointers ahead (found a matching character). Otherwise, move only j to continue searching in t. Step 3 (Final Check): If all characters of s are matched (i == len(s)), return True; otherwise, False. This simple yet efficient approach ensures we verify order preservation without needing consecutive matches. 🕒 Time Complexity: O(n) — traverse through string t once. 💾 Space Complexity: O(1) — constant extra space used. 📁 File: https://lnkd.in/gnPitwpj 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem reinforced the two-pointer technique, teaching me how to efficiently track sequences without extra data structures. It also served as a foundational exercise for more complex problems like Longest Common Subsequence and Sequence Matching. A great reminder that elegant solutions often come from simple logic and careful pointer movement. ✅ Day 110 complete — traced hidden letters across timelines to confirm their order! ✨🔤🎯 #LeetCode #DSA #Python #TwoPointers #String #Greedy #Subsequence #100DaysOfCode #DailyCoding #InterviewPrep #GitHubJourney
To view or add a comment, sign in
-
🚀 DSA Challenge – Day 92 Problem: N-Queens Puzzle ♟️👑 This classic problem beautifully combines recursion, backtracking, and constraint satisfaction — a true test of algorithmic thinking and precision. 🧠 Problem Summary: You are given an integer n, representing an n × n chessboard. The goal is to place n queens such that no two queens attack each other — meaning no two share the same row, column, or diagonal. We must return all distinct board configurations that satisfy this condition. ⚙️ My Approach: 1️⃣ Use backtracking to try placing one queen per row. 2️⃣ Maintain three sets to track attacks: col → columns already occupied. positiveDiag (r + c) → major diagonals. negativeDiag (r - c) → minor diagonals. 3️⃣ For each row, place a queen only if it’s not under attack, then recurse for the next row. 4️⃣ Once all queens are placed, record the configuration as a valid solution. 📈 Complexity: Time: O(n!) → Since we explore all valid placements row by row. Space: O(n²) → For the board representation and recursion stack. ✨ Key Takeaway: The N-Queens problem teaches the art of constraint-driven backtracking — building solutions step by step while eliminating invalid paths early. It’s a perfect showcase of logical pruning in action. ⚡ 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #Backtracking #Recursion #NQueens #Algorithms #Python #Optimization #Chessboard #InterviewPrep #EfficientCode #TechCommunity #LearningByBuilding #CodeEveryday
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 96 Problem: String to Integer (atoi) 🔢➡️💻 This is a classic implementation problem that tests careful handling of edge cases, parsing logic, and boundary conditions. 🧠 Problem Summary: Implement the function myAtoi(string s) that converts a string into a 32-bit signed integer following specific parsing rules. Steps to follow: 1️⃣ Ignore leading whitespaces. 2️⃣ Check the sign (+ or -). 3️⃣ Read digits until a non-digit character is found. 4️⃣ Handle overflow/underflow by clamping the number within the 32-bit signed integer range: Range = [−2³¹, 2³¹ − 1] 5️⃣ Return the final integer. ⚙️ My Approach: Trim leading spaces using lstrip(). Identify the sign based on the first non-space character. Iterate through the string and build the number digit by digit. Multiply by the sign and ensure the result stays within integer limits using max() and min(). 📈 Complexity Analysis: Time: O(n) — traverse each character once. Space: O(1) — only a few variables used. ✨ Key Takeaway: This problem is a great example of careful boundary handling and parsing logic — it’s not just about coding, but about thinking through every possible input case. 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #Python #CodingChallenge #myAtoi #StringParsing #AlgorithmDesign #InterviewPrep #TechCommunity #LearningEveryday
To view or add a comment, sign in
-
-
#Day67 of my LeetCode Journey 🚀 Starting with Recursion problems ! 🧩 Question #8 – String to Integer (atoi) (Medium) Brute Force Approach: 1) Convert the string manually step-by-step remove whitespaces, handle signs, read digits, and clamp values. 2) Check for invalid inputs and handle edge cases like overflow/underflow explicitly. 3) Use iterative parsing to process characters sequentially. - Time Complexity: O(N) - Space Complexity: O(1) Optimal (Recursive) Approach: 1) Use recursion to simplify the parsing process each helper function handles one part (like skipping spaces, checking sign, removing zeros, or reading digits). 2) Extract digits recursively until a non-numeric character appears. 3) Convert digits to an integer and clamp it within the 32-bit signed range. - Time Complexity: O(N) - Space Complexity: O(N) (due to recursive calls) ✨ That’s it for Day 67. The journey continues — see you on Day 68. Happy coding! 🚀 #Day67 #LeetCodeJourney #LeetCode #Recursion #String #Atoi #Python #DSA #CodingPrep
To view or add a comment, sign in
-
-
Day 33 / 100 – Maximum Average Subarray (LeetCode #643) Today’s challenge was about finding a contiguous subarray of length k with the maximum average. At first glance, it seems simple, but the key is doing it efficiently. By using a sliding window, I avoided recalculating sums for every subarray, which makes the solution both fast and elegant. This problem reminded me that small optimizations in logic can lead to huge improvements in performance, and thinking carefully about how to structure your solution is just as important as solving the problem itself. 🔍 Key Learnings Sliding window technique updates the sum in constant time for each step. Keeping track of the maximum sum while iterating avoids unnecessary computations. Always ensure floating-point division for correct average calculations. 💭 Thought of the Day Efficiency in coding comes from thinking smart, not from brute force. Sliding window allowed me to write clean and readable solutions while handling all edge cases. Today reinforced that solving problems isn’t just about getting a correct answer — it’s about writing solutions that are elegant, efficient, and scalable. 🔗 Problem Link:https://lnkd.in/gCVb4_pu #100DaysOfCode #Day33 #LeetCode #Python #SlidingWindow #ProblemSolving #Algorithms #DataStructures #CodingChallenge #CodeEveryday #LearningJourney #TechGrowth #Efficiency #CleanCode #PythonProgramming
To view or add a comment, sign in
-
-
💡 Day 17 of 30 – LeetCode Challenge: Word Search (Backtracking) Today’s problem tested my understanding of DFS (Depth-First Search) and Backtracking — a key algorithmic concept used in exploring possible paths or configurations in grids, trees, and graphs. 🧩 Problem Summary We are given an m x n character grid (board) and a string word. We must determine if the word exists in the grid by moving horizontally or vertically through adjacent cells. Each cell can be used only once per word construction. ⚙️ Example Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]] word = "ABCCED" Output: true 📖 Explanation: The path A → B → C → C → E → D forms the word “ABCCED” through valid adjacent cells. 🧠 Approach 1. Traverse every cell in the grid. 2. If the character matches the first letter of word, start a DFS. 3. Explore all 4 directions — up, down, left, right — recursively. 4. Mark cells as visited (temporarily) to prevent reuse. 5. Backtrack after exploring each path (restore cell value). 6. Return True as soon as the word is found. ⏱ Complexity Analysis Time Complexity O(m * n * 4^L) → where L = length of word Space Complexity O(L) (Recursion stack) 🧩 Key Learnings ✨ Learned how DFS + Backtracking can explore all potential paths efficiently. ✨ Importance of restoring state (backtracking) after recursive exploration. ✨ Strengthened my problem-solving in grid-based traversal problems. Backtracking is like exploring a maze — you move forward when possible and step back when you hit a dead end. #Day17 #LeetCode #Backtracking #DFS #WordSearch #CodingChallenge #Python #DSA #WomenWhoCode #ProblemSolving #MTech #LearningJourney
To view or add a comment, sign in
-
-
🧩 Day 38 / 100 – Transpose Matrix (LeetCode #867) Today’s problem focused on understanding matrix manipulation — specifically, the Transpose of a matrix. Transposing means flipping a matrix over its diagonal, turning rows into columns and columns into rows. It’s a simple concept but helps strengthen 2D array traversal logic — especially how to navigate nested loops cleanly and avoid index confusion. This was a good reminder that clarity and structure matter just as much as complexity. 🔍 Key Learnings Transposing a matrix means swapping element positions — matrix[i][j] → result[j][i]. Use nested loops efficiently to fill the new matrix with swapped indices. Always keep track of dimensions — rows become columns and vice versa. 💭 Thought of the Day Even small transformations like a transpose can teach big lessons in clean logic. Sometimes we overthink “hard” problems, but mastering basics like matrix traversal builds the foundation for solving advanced ones like rotation or dynamic programming grids. 🔗 Problem Link:https://lnkd.in/gHKB9h4b #100DaysOfCode #Day38 #LeetCode #Python #Matrix #Transpose #ProblemSolving #Algorithms #DataStructures #CodingChallenge #CodeEveryday #LearningJourney #CleanCode #TechGrowth #PythonProgramming
To view or add a comment, sign in
-
-
🚀 DSA Progress – Day 117 ✅ Problem #946: Validate Stack Sequences 🧠 Difficulty: Medium | Topics: Stack, Simulation, Array 🔍 Approach: Implemented a stack-based simulation to validate push and pop sequences: Step 1 (Initialization): Create an empty stack st and pointers i and j for pushed and popped arrays. Step 2 (Push Elements): Iterate through pushed, pushing each element onto the stack. Step 3 (Pop Check): After each push, check if the top of the stack matches popped[j]. While the stack is not empty and top matches popped[j], pop from the stack and increment j. Step 4 (Final Validation): After processing all elements, if the stack is empty, the sequences are valid; otherwise, they are invalid. This approach simulates the real stack behavior step by step, ensuring that push/pop operations match the given sequences. 🕒 Time: O(n), each element is pushed and popped at most once. 💾 Space: O(n), for the stack. 📁 File: https://lnkd.in/gJJBfAjc 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem demonstrates how to simulate stack operations efficiently. It reinforced understanding of stack behavior and pointer manipulation. Using a simple stack and two pointers made the solution clean and intuitive. ✅ Day 117 complete — mastered the art of validating stack choreography! 🧩📦✨ #LeetCode #DSA #Python #Stack #Simulation #Array #DailyCoding #InterviewPrep #GitHubJourney
To view or add a comment, sign in
-
🚀 Day 42 of #100DaysOfCode — Leetcode + HackerRank Edition! Today’s challenge was a deep dive into string-based arithmetic — no shortcuts allowed! 🧩 multiply(num1: str, num2: str) -> str — Multiply two non-negative integers represented as strings, without using int() or BigInteger. 📌 Challenge: → No built-in conversion from string to integer → No BigInteger libraries → Just pure digit-by-digit simulation, like manual multiplication → Example: num1 = "123", num2 = "456" ✅ Output: "56088" 🔍 Approach: → Reversed both strings to simplify digit placement → Used ASCII math: ord(char) - ord('0') to extract digits → Stored intermediate products in an array of size len(num1) + len(num2) → Managed carry manually and built the final string from the result array 💡 What made it click: → Realized that each digit product lands at position i + j in the result array → Practiced dry runs to visualize how "123" * "456" becomes "56088" → Saw how carry propagation works across the array → Appreciated how reversing strings simplifies index math 📚 What I learned: ✅ How to simulate arithmetic without integer conversion ✅ How to use ASCII tricks to decode digits ✅ How to manage carry and build results step-by-step ✅ The power of dry runs to debug and understand logic Have you ever built a calculator or tackled string-based math problems? Let’s swap strategies and visual walkthroughs 💬 #Day42 #Leetcode #Python #StringManipulation #ASCIITricks #LearnInPublic #CodeNewbie #TechJourney #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
Day 7 of My Rust Journey 🦀 : Iterator enumerate() & String Slices Today I explored the enumerate() method and its practical applications in string processing. The key learning: enumerate() wraps iterators to provide both index and value as tuples, eliminating manual index tracking. I built a function to find the first word in a string using enumerate() with byte iteration, then returned it as a string slice. The real challenge came when the compiler caught a borrowing violation - trying to modify a string while an immutable slice was still in use. 📝 Detailed notes: https://lnkd.in/gH6F4t-s #Rust #100DaysOfCode #LearnInPublic #SystemsProgramming
To view or add a comment, sign in