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

LeetCode #726: Number of Atoms, Stack of Count Maps

Brute To Best

0:00 / 0:00

LeetCode #726: Number of Atoms, Stack of Count Maps

9 просмотров · 2 нед. назад
Brute To Best
101 подписчик
9 просмотров · 2 нед. назад
Brute to Best: every LeetCode problem, from the naive solution to the optimal one. In this video: The problem: given a chemical formula with nested parentheses and multipliers, return the count of each atom, with the atom names in sorted order. Brute force: expand the formula as text, repeating each group by its multiplier, then count. This blows up with deep nesting. The key insight: use a stack of maps. "(" pushes a new empty map. ")" followed by a number multiplies the top map and merges it into the map below. Parse an atom as one uppercase letter followed by any lowercase letters, then read its count (1 if there is no number). At the end, sort the atom names and write each one with its count, leaving out counts of 1. Dry run on K4(ON(SO3)2)2: SO3 × 2 gives S2 O6, then ON(...) × 2 gives N2 O14 S4. Adding K4 and sorting gives K4N2O14S4. Complexity: O(N²) time in the worst case for nested merges and O(N) space. Problem: https://leetcode.com/problems/number-... Related: Decode String (394), Basic Calculator (224), Parse Lisp Expression (736) 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 #leetcode726 #numberofatoms #stack #hashmap #parsing #string #recursion #hard #coding #codinginterview #dsa #python #faang #brutetobest