Перейти к содержимому

LeetCode #767: Reorganize String, Fill Even Slots With the Most Frequent Letter

Brute To Best

0:00 / 0:00

LeetCode #767: Reorganize String, Fill Even Slots With the Most Frequent Letter

5 просмотров · 15 ч назад
Brute To Best
105 подписчиков
5 просмотров · 15 ч назад
Brute to Best: every LeetCode problem, from the naive solution to the optimal one. In this video: The problem: rearrange the string so that no two neighbouring characters are the same, or return an empty string if that can't be done. Brute force: try every permutation, which is factorial. The key insight: it can only be done if the most common letter appears at most (n + 1) / 2 times. Place the most common letter in the even indices 0, 2, 4 and so on. Then put the other letters in the remaining even slots, and wrap around to the odd ones. Another option: a max-heap that always places the two most common remaining letters next, which takes O(N log 26). Dry run: aab becomes aba. aaab returns an empty string because a appears 3 times out of 4. Complexity: O(N) time and O(1) space with 26 counts. Problem: https://leetcode.com/problems/reorgan... Related: Task Scheduler (621), Rearrange String k Distance Apart (358), Distant Barcodes (1054) Full Brute to Best playlist on the channel. Subscribe for a new LeetCode problem, solved from brute force to the best solution, every day. Hashtags #leetcode #leetcode767 #reorganizestring #greedy #heap #priorityqueue #counting #string #medium #coding #codinginterview #dsa #python #amazon #brutetobest