Incremental Memory Leak — LeetCode 1860 Python Solution

MediumMathSimulation
Problem
#1860
Reading time
2 min

The problem

You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.

Example

Input
memory1 = 2, memory2 = 2
Output
[3,1,0]
Explanation
The memory is allocated as follows:

Python solution

Python
class Solution:
    def memLeak(self, memory1: int, memory2: int) -> List[int]:
        i = 1
        while i <= max(memory1, memory2):
            if memory1 >= memory2:
                memory1 -= i
            else:
                memory2 -= i
            i += 1
        return [i, memory1, memory2]

Complexity

MeasureComplexity
TimeO(\sqrt{m_1+m_2}), where m_1 and m_2 are the sizes of the two memory sticks respectively
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1860. Incremental Memory Leak is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1860. Incremental Memory Leak?
LeetCode 1860. Incremental Memory Leak is rated Medium on LeetCode.
What is the time complexity of LeetCode 1860. Incremental Memory Leak?
The Python solution on this page runs in O(\sqrt{m_1+m_2}), where m_1 and m_2 are the sizes of the two memory sticks respectively.
What is the space complexity of LeetCode 1860. Incremental Memory Leak?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1860. Incremental Memory Leak cover?
LeetCode 1860. Incremental Memory Leak is tagged Math and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview