Today I solved LeetCode 3321 - Find X-Sum of All K-Long Subarrays II (Hard) #day14 of #1001DaysOfCode The challenge is to compute the “x-sum” for every subarray of length k. Instead of simply summing values, we first: Count occurrences of each number in the subarray Select the top x most frequent elements (breaking ties by choosing the larger value) Then sum only those selected elements with all their occurrences A direct recalculation for every sliding window would be too slow, so the key idea was to maintain frequency counts incrementally and keep the top-x elements efficiently balanced using two heaps. To solve it, I used: A sliding window to move across the array efficiently A frequency map to track counts Two heaps (in for top-x elements, out for remaining elements) A dynamic rebalancing step to ensure correctness as counts change Detailed explanation + code here: https://lnkd.in/dD4e5WNh #LeetCode #Python #DataStructures #Heaps #Algorithms #CodingChallenge #SoftwareEngineering #CompetitiveProgramming
Radoslav Petkov’s Post
More Relevant Posts
-
🚀 Day 3 of #100DaysofDSA Today’s focus was on the “Set Matrix Zeroes” problem — a classic array-matrix question that tests both logic and optimization thinking It began with the brute-force idea: storing all zero positions and then marking corresponding rows and columns later. It works but takes O(m × n) time and O(m + n) extra space. Next, then explored a better approach using two auxiliary arrays to track which rows and columns should be zeroed. This improved the clarity but still consumed additional memory and space. Finally, then to reduce the complexity I tackled the optimal solution, which achieves O(1) extra space by using the first row and first column of the matrix itself as markers. A small Boolean flag handles the edge case when the first row contains a zero. This subtle observation transforms the logic completely — turning a memory-heavy method into a clean in-place algorithm. It was a good reminder that optimization isn’t just about speed — it’s about finding elegance in constraints. #100DaysOfDSA #MatrixProblems #Optimization #SpaceComplexity #Python #ProblemSolving
To view or add a comment, sign in
-
-
Day 16 of #100DaysOfLeetCode Today’s problem focused on substring counting within binary strings and required an efficient approach to handle potentially large input sizes without generating every substring explicitly. 1. Number of Substrings With Only 1s The task was to count the total number of substrings that consist entirely of the character '1', with the final result taken modulo (10^9 + 7). Instead of constructing the substrings, the key insight is that each continuous block of 1s contributes a predictable number of valid substrings. 🔹 My Approach: Iterated through the string while tracking the current streak length of consecutive 1s. Each time a block ended, computed the number of substrings from that block using the formula: k*(k+1)/2 where k is the length of the streak. Added the total from each block to the final answer, applying the modulo constraint throughout. Completed the process with a final update for any trailing block of 1s. What I Learned: This problem reinforces how recognizing mathematical patterns within sequences can transform a brute-force solution into a simple linear scan. Efficient substring counting often comes down to understanding structure rather than enumerating possibilities. 📊 Complexity Analysis: Time Complexity: O(n) — single pass over the string. Space Complexity: O(1) — constant space approach. #day16 #100daysofleetcode #leetcode #DSA #python #leetcodes #striver
To view or add a comment, sign in
-
-
🚀 LeetCode Daily — Problem #350: Intersection of Two Arrays II Today I solved another interesting array problem that focuses on finding the intersection between two integer arrays — including duplicates. 💡 Problem Statement: Given two arrays, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays. 🧠 My Approach: I used the two-pointer technique after sorting both arrays: Sort both nums1 and nums2. Use two pointers i and j to traverse both arrays. Compare elements: If equal → add to result and move both pointers. If smaller → move the smaller pointer. Continue until one array ends. 🧩 Time Complexity: Sorting: O(n log n + m log m) Traversal: O(n + m) ✅ Overall: Efficient and clean solution 🏆 Result: ⏱ Runtime: 3 ms (Beats 40.41%) 💾 Memory: 17.75 MB (Beats 93.43%) Each problem like this strengthens my understanding of two-pointer patterns and efficient array traversal in Python. #LeetCode #Python #DSA #CodingJourney #ProblemSolving #Arrays #TwoPointers #Programming
To view or add a comment, sign in
-
-
Day 31 / 100 – Add Strings (LeetCode #415) Today’s challenge was all about simulating manual addition without using any built-in integer conversions. Given two numbers as strings, the task was to return their sum — also as a string. This problem really emphasized the importance of breaking problems into small, logical steps rather than relying on shortcuts. 🔍 Key Learnings Recreated the digit-by-digit addition process using ASCII values. Practiced handling carry-over efficiently while iterating backward. Strengthened my understanding of string manipulation and arithmetic logic. 💭 Thought of the Day True problem-solving isn’t about using built-ins — it’s about understanding how things work underneath. Today reminded me that mastery grows when we rebuild the basics from scratch, not when we avoid them. 🔗 Problem Link: https://lnkd.in/gHMt9vj9 #100DaysOfCode #Day31 #LeetCode #Python #ProblemSolving #StringManipulation #Algorithms #DataStructures #CodingChallenge #CodeEveryday #TechGrowth #LearningJourney
To view or add a comment, sign in
-
-
Today I worked on a classic string problem: Finding the length of the longest substring that contains no repeated characters. 🧠 What the problem asks: Given a string, identify the longest continuous sequence where all characters are unique, and return its length. 📌 Key Observations: A substring must be continuous (not scattered like a subsequence) As soon as a character repeats, the current window becomes invalid The goal is to maintain a window of unique characters only 🔍 How I approached it: I used the Sliding Window technique with two pointers. This helped me: Expand the window when characters are unique Shrink it when duplicates appear Track the maximum length efficiently This approach avoids rechecking characters repeatedly and keeps the solution optimal. ✔ Example Insights: "abcabcbb" → longest substring: "abc" → length 3 "bbbbb" → "b" → length 1 "pwwkew" → "wke" → length 3 💡 Takeaway: This problem reinforces how powerful sliding window techniques are for real-world string and array challenges. Great practice for improving logic, efficiency, and pattern recognition. #LeetCode #CodingPractice #Python #Algorithms #100DaysOfCode #SlidingWindow #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
💡 Day 96 of My #100DaysOfCode Challenge Today’s problem: LeetCode 3432 – Count Partitions with Even Sum Difference ⚙️ 📘 Problem Statement: Given an integer array nums, we need to count the number of ways to partition it into two non-empty parts such that the difference between their sums is even. ✅ Approach: Calculate the total sum of the array. Traverse the array while maintaining a running left sum. At each partition index, compute the right sum = totalSum - leftSum. Check if (leftSum - rightSum) is even → if yes, increase the count. 💻 Time Complexity: O(n) 🧠 Space Complexity: O(1) 🔥 Key Learnings: Strengthened understanding of prefix sums Practiced modular arithmetic in array partitions Improved analytical thinking on even-odd relationships #LeetCode #Python #CodingChallenge #100DaysOfCode #ProblemSolving #DataStructures #Algorithms #LearningEveryday
To view or add a comment, sign in
-
-
💻 2011: Final Value of Variable After Performing Operations Today’s challenge was a simple yet interesting warm up problem that tests how efficiently we can track changes in a variable through a series of operations. 🧠 Concept: We start with X = 0, and perform operations like ++X, X++, --X, and X--. Each increment or decrement modifies X by 1, the task is to return the final value after performing all operations. ⚙️ Approach: - A straightforward solution: - Iterate through all operations. - Increment count by 1 for ++ or X++. - Decrement count by 1 for -- or X--. - Return the final count. Even though it’s an easy problem, it’s a great reminder that clarity and precision matter, small details in logic can make a big difference. #LeetCode #Python #CodingPractice #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
✅ Learned to solve “Remove Duplicates from Sorted Array” (in-place, O(n) time, O(1) space)! Sorted input means every duplicate sits next to its twin—perfect setup for the two-pointer pattern: scan once, write uniques forward, and return the count k while keeping the first k positions clean and ordered. What clicked: - Two pointers: one scans, one writes uniques forward - Skip repeats deterministically thanks to sorting - Edge cases covered: empty array, all duplicates, negatives, mixed ranges Level-ups next: “Remove Duplicates II” (allow at most twice) and “Remove Element” to deepen the pattern muscle. What’s your favorite twist on this technique? 🚀 #LeetCode #TwoPointers #Arrays #InPlace #DSA #Algorithms #InterviewPrep #ProblemSolving #TimeComplexity #CodingChallenge #Python #SoftwareEngineering
To view or add a comment, sign in
-
-
🔍 Day 44 DSA Challenge – Problem #33: Search in Rotated Sorted Array 📌 Problem Statement: Given a sorted array nums that may have been rotated at an unknown pivot, find the index of a target value. Return -1 if the target doesn’t exist. The solution must run in O(log n) time. ⚙️ How I Solved It: Applied a modified binary search: Identify which half (left or right) is sorted. Narrow the search to the half where the target could exist. Repeat until the target is found or search space is exhausted. 📊 Performance Stats: ⏱ Runtime: 0 ms (⚡ beats 100%) 💾 Memory: 12.65 MB (beats 42.49%) ✅ Testcases Passed: 196 / 196 🧠 Key Takeaway: Understanding array properties like rotation and leveraging binary search ensures optimal search performance in logarithmic time. #LeetCode #BinarySearch #RotatedArray #Problem33 #Python #DSA #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
Day 3 of #100DaysOfLeetCode Problem: 167. Two Sum II – Input Array Is Sorted Category: Arrays / Two Pointers Today’s challenge was all about finding two numbers in a sorted array that add up to a given target. Since the array is already sorted, using two pointers gives an elegant O(n) solution — no need for extra space! 🧠 Key Learnings: Initialized pointers at both ends (l = 0, r = n-1). If the sum is smaller than the target → move left pointer rightward. If the sum is greater → move right pointer leftward. Found the exact indices in linear time using smart pointer movement. 💡Time Complexity: O(n) 💡 Space Complexity: O(1) 🎯 Takeaway: When the array is sorted, two pointers can replace complex hash-based logic, simplifying both time and space usage. Staying consistent and learning one problem at a time! 💪 #LeetCode #100DaysOfCode #ProblemSolving #CodingJourney #Arrays #TwoPointers #Python #AIEngineer #Consistency
To view or add a comment, sign in
-
More from this author
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