LeetCode 1248: Count Number of Nice Subarrays Solution
Master LeetCode problem 1248 (Count Number of Nice Subarrays), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1248. Count Number of Nice Subarrays
Problem Explanation
Explanation
To solve this problem, we can use a sliding window approach. We will maintain two pointers - left and right, and keep expanding the window until we have exactly k odd numbers in the window. For each valid window, we can calculate the number of subarrays that can be formed with that window as a nice subarray. We can keep track of the count of such subarrays and return the final result.
- Initialize left = 0, right = 0, count = 0, oddCount = 0, result = 0
- Iterate over the array while moving the right pointer:
- If nums[right] is odd, increment oddCount
- While oddCount == k, increment count for each valid window and move the left pointer:
- While nums[left] is not odd, increment count and move left
- After exiting the inner loop, calculate the number of subarrays that can be formed with the current window
- Increment result by the count of subarrays
- Move the left pointer to continue the search for more valid windows
- Return the final result
Time Complexity: O(N) where N is the number of elements in the array. Space Complexity: O(1)
Solution Code
class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int left = 0, right = 0, count = 0, oddCount = 0, result = 0;
for (right = 0; right < nums.length; right++) {
if (nums[right] % 2 == 1) {
oddCount++;
}
while (oddCount == k) {
count = 0;
while (oddCount == k) {
if (nums[left] % 2 == 0) {
count++;
} else {
oddCount--;
}
left++;
}
result += count;
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1248 (Count Number of Nice Subarrays)?
This page provides optimized solutions for LeetCode problem 1248 (Count Number of Nice Subarrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1248 (Count Number of Nice Subarrays)?
The time complexity for LeetCode 1248 (Count Number of Nice Subarrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1248 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1248 in Java, C++, or Python.