Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK

Автор: codestorywithMIK

Загружено: 2024-06-22

Просмотров: 14681

Описание:

iPad PDF Link - https://github.com/MAZHARMIK/Intervie...
Whatsapp Community Link : https://www.whatsapp.com/channel/0029...
This is the 93rd Video of our Playlist "Array 1D/2D : Popular Interview Problems" by codestorywithMIK

In this video we will try to solve a very good Array based Problem : Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK

I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
We will do live coding after explanation and see if we are able to pass all the test cases.
Also, please note that my Github solution link below contains both C++ as well as JAVA code.

Problem Name : Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK
Company Tags : will update soon
My solutions on Github(C++ & JAVA) : https://github.com/MAZHARMIK/Intervie...
Leetcode Link : https://leetcode.com/problems/count-n...


My DP Concepts Playlist :    • Roadmap for DP | How to Start DP ? | Topic...  
My Graph Concepts Playlist :    • Graph Concepts & Qns - 1 : Graph will no m...  
My Recursion Concepts Playlist :    • Introduction | Recursion Concepts And Ques...  
My GitHub Repo for interview preparation : https://github.com/MAZHARMIK/Intervie...
Instagram :   / codestorywithmik  
Facebook :   / 100090524295846  
Twitter :   / cswithmik  
Subscribe to my channel :    / @codestorywithmik  

╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
╠╗║╚╝║║╠╗║╚╣║║║║║═╣
╚═╩══╩═╩═╩═╩╝╚╩═╩═╝

Summary :
Approach 1: Using Prefix Sum and Hashmap

Time Complexity (T.C): O(n)
Space Complexity (S.C): O(n)
This approach leverages the prefix sum technique combined with a hashmap to efficiently count subarrays with exactly k odd numbers.

Initialization:

mp (unordered_map) to store the frequency of prefix sums.
Variables: n (length of nums), count (result count), and currSum (current prefix sum).
Iterate Through Array:

For each element, update currSum by adding 1 if the element is odd (nums[i] % 2), else add 0.
Check if currSum - k exists in mp. If it does, increment count by the frequency of currSum - k.
Update mp to include the current currSum.
This method ensures that each subarray's prefix sum is calculated in linear time, and the hashmap provides efficient lookups for the required subarray sums.

Approach 2: Sliding Window (Khandani Template with a Twist)

Time Complexity (T.C): O(n)
Space Complexity (S.C): O(1)
This approach utilizes a sliding window technique to dynamically count subarrays containing exactly k odd numbers.

Initialization:

Variables: n (length of nums), oddCount (number of odd numbers in the current window), count (subarrays ending at the current position), result (total count of valid subarrays), and two pointers i and j (window boundaries).
Sliding Window:

Iterate with j from 0 to n-1. For each element:
If the element is odd, increment oddCount and reset count to 0.
While oddCount equals k, increment count and adjust the window by incrementing i and decreasing oddCount if the element at i is odd.
Add count to result.
This method maintains a sliding window that expands and contracts based on the number of odd numbers, ensuring efficient computation in linear time with constant space.



✨ Timelines✨
00:00 - Introduction

#coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook #leetcode #computerscience #leetcodesolutions #leetcodequestionandanswers #code #learning #dsalgo #dsa #newyear2024

Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Minimum Number of K Consecutive Bit Flips | 3 Approaches | Leetcode 995 | 3191 | codestorywithMIK

Minimum Number of K Consecutive Bit Flips | 3 Approaches | Leetcode 995 | 3191 | codestorywithMIK

Подсчёт количества подмассивов Nice — Leetcode 1248 — Python

Подсчёт количества подмассивов Nice — Leetcode 1248 — Python

Удаление дубликатов из списка | Выдержка из AHK Hero

Удаление дубликатов из списка | Выдержка из AHK Hero

Shortest Subarray with Sum at Least K | Already Studied Concept | Leetcode 862 | codestorywithMIK

Shortest Subarray with Sum at Least K | Already Studied Concept | Leetcode 862 | codestorywithMIK

Binary Subarrays With Sum | 2 Approaches | Detailed Explanation | Leetcode 930 | codestorywithMIK

Binary Subarrays With Sum | 2 Approaches | Detailed Explanation | Leetcode 930 | codestorywithMIK

LLM fine-tuning или ОБУЧЕНИЕ малой модели? Мы проверили!

LLM fine-tuning или ОБУЧЕНИЕ малой модели? Мы проверили!

Maximize Area of Square Hole in Grid | Detailed Thought Process | Leetcode 2943 | codestorywithMIK

Maximize Area of Square Hole in Grid | Detailed Thought Process | Leetcode 2943 | codestorywithMIK

Удаляем свои фото, выходим из чатов, скрываем фамилию? Как избежать штрафов

Удаляем свои фото, выходим из чатов, скрываем фамилию? Как избежать штрафов

Почему Собаки Вдруг ЗАЛЕЗАЮТ На Вас? (Причина шокирует)

Почему Собаки Вдруг ЗАЛЕЗАЮТ На Вас? (Причина шокирует)

Что такое квантовая теория

Что такое квантовая теория

Революция в Иране. Как Марко Рубио Сносит Режимы? | Быть Или

Революция в Иране. Как Марко Рубио Сносит Режимы? | Быть Или

Алгоритмическое mock-собеседование | Ex-Team Lead Яндекс

Алгоритмическое mock-собеседование | Ex-Team Lead Яндекс

Событий в 2026 хватит на три президентских срока

Событий в 2026 хватит на три президентских срока

Как устроен эскалатор? [Veritasium]

Как устроен эскалатор? [Veritasium]

Почему простые числа образуют эти спирали? | Теорема Дирихле и пи-аппроксимации

Почему простые числа образуют эти спирали? | Теорема Дирихле и пи-аппроксимации

Сергей Алексашенко* и Лиза Аникина. Цена вопроса / 14.01.26 @SergeyAleksashenkoSr​

Сергей Алексашенко* и Лиза Аникина. Цена вопроса / 14.01.26 @SergeyAleksashenkoSr​

Параметр с МОДУЛЕМ для ЕГЭ 2026 за 15 минут!

Параметр с МОДУЛЕМ для ЕГЭ 2026 за 15 минут!

Алгоритмы и структуры данных ФУНДАМЕНТАЛЬНЫЙ КУРС от А до Я. Графы, деревья, хеш таблицы и тд

Алгоритмы и структуры данных ФУНДАМЕНТАЛЬНЫЙ КУРС от А до Я. Графы, деревья, хеш таблицы и тд

Слышал, их ПРОКАЧАЛИ!💪 POCO M8 PRO и POCO M8 - расскажу ПРАВДУ

Слышал, их ПРОКАЧАЛИ!💪 POCO M8 PRO и POCO M8 - расскажу ПРАВДУ

1248. Count Number of Nice Subarrays | Prefix Sums | Sliding Window | Same as Leetcode 930

1248. Count Number of Nice Subarrays | Prefix Sums | Sliding Window | Same as Leetcode 930

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com