Terrible LeetCode in Kotlin: #525 Contiguous Array
Another day, another LeetCode question (for now). Today, I'm running through #525 Contiguous Array. The problem provides an array of integers, with the expected output of an integer that represents the length of the longest subarray that can be created which has the same number of 1s and 0s.
This problem stumped me (as will the one coming later in the day). I intially thought that a sliding window approach could work, but quickly ruled that out as there wasn't any really good way to know which items that our subarray would eventually cover. In the absence of that, a brute force method would have been too slow.
I also thought about dynamic programming, including using a "score" where 0 increments and 1 decrements, but couldn't come to a clean solution. Looking at the answer provided by LeetCode, it turns out that I was partially correct - the main key here is that when we reach a "score" that we have already achieved, we know that we can build an array of balanced 1s and 0s because the only way for the same score to occur is if there were an equal number of increments/decrements to reach that score. We use a hashmap to keep track of the score, and then return the maximum. This takes O(n) time, and O(n) space, where n is the number of elements within our array.
I work in Kotlin as my LeetCode programming language because my current focus is on Android app development. Kotlin is interoperable with Java, so the solution should be relatively similar albeit with some more boilerplate checks for nulls and such.
Current Grind:
- Grind75 list, 22 weeks/16 hours per week, [101/169]
(https://www.techinterviewhandbook.org/grind75)
Chapters:
00:00 - Problem discussion
30:03 - Solution Discussion (Hashmap)
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Terrible LeetCode in Kotlin: #525 Contiguous Array», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.