#1860
Incremental Memory Leak
MediumMathSimulationSimulationGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of simulating each second, we can calculate the maximum time until the program crashes based on the available memory. This allows us to find the crash time directly without iterating through every second.
⚙️
Algorithm
3 steps- 1Step 1: Determine the total memory available and the maximum time it can run before crashing.
- 2Step 2: Use a loop to allocate memory until we reach the point where neither stick can allocate the required bits.
- 3Step 3: Calculate the remaining memory after the last successful allocation to determine the crash time.
solution.py14 lines
1def incremental_memory_leak(memory1, memory2):
2 time = 0
3 while True:
4 time += 1
5 if memory1 >= memory2:
6 if memory1 < time:
7 return [time, memory1, memory2]
8 memory1 -= time
9 else:
10 if memory2 < time:
11 return [time, memory1, memory2]
12 memory2 -= time
13
14print(incremental_memory_leak(8, 11))ℹ
Complexity note: The time complexity is O(n) because we only iterate through the seconds until we find the crash point, which is linear with respect to the number of seconds.
- 1Memory allocation is based on the available memory of each stick.
- 2The program crashes when neither stick can allocate the required bits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.