Competitive Programming: Counting Nice Subarrays with Hashing + Prefix Sum

🚀 𝐂𝐨𝐦𝐩𝐞𝐭𝐢𝐭𝐢𝐯𝐞 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠 | 𝐇𝐚𝐬𝐡𝐢𝐧𝐠 + 𝐏𝐫𝐞𝐟𝐢𝐱 𝐒𝐮𝐦 | 𝐂𝐨𝐮𝐧𝐭 𝐍𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 𝐍𝐢𝐜𝐞 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲𝐬 💡 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐬𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭: Given an integer array nums and an integer k, a subarray is called nice if it contains exactly k odd numbers. Your task is to count how many such subarrays exist. 🧠 Why this problem is important? This is a classic example where brute force fails (O(n²)), and we optimize using Hashing + Prefix Sum to achieve O(n) time complexity . 📌 𝐊𝐞𝐲 𝐈𝐧𝐬𝐢𝐠𝐡𝐭 : Instead of working with the actual values, convert the array into a representation of odd counts (0 & 1) and track cumulative sums. ⚙️ 𝐎𝐩𝐭𝐢𝐦𝐚𝐥 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 (𝐇𝐚𝐬𝐡𝐢𝐧𝐠 + 𝐏𝐫𝐞𝐟𝐢𝐱 𝐒𝐮𝐦): Maintain a running count of odd numbers using prefix sum. Use a hash map to store frequency of prefix sums. For each index, check how many times (current_sum - k) has appeared. This directly gives the number of valid subarrays ending at that index. 🔥 Why this works? Because: If sum[j] - sum[i] = k, then the subarray (i+1 → j) has exactly k odd numbers. 📊 Complexity: Time: O(n) Space: O(n) 🔗 Code (Optimal Approach): 👉 https://lnkd.in/dpEsCUcP 💬 Pro Tip: This pattern is widely used in problems involving: Subarrays with given sum Binary transformations Counting problems using prefix frequencies #programming #competitiveprogramming #coding #datastructures #algorithms #cpp #hashing #prefixsum

  • graphical user interface, text, application, chat or text message

Great explanation, made prefix sums feel intuitive

See more comments

To view or add a comment, sign in

Explore content categories