Incremental Memory Leak

medium math simulation

Problem

You have two memory sticks with memory1 and memory2 bits available. A faulty program runs in seconds counted from 1. On the second numbered i, the program tries to allocate exactly i bits of memory.

The allocation always goes to whichever stick currently has more bits available; if both sticks have the same amount, it goes to the first stick. The program crashes at the first second i where i bits cannot be allocated to either stick (both sticks have fewer than i bits free).

Return an array [crashTime, memory1, memory2]: the second on which it crashed, and the bits still available in each stick at that moment.

Inputmemory1 = 2, memory2 = 2
Output[3, 1, 0]
Second 1: tie, allocate 1 to stick 1 → (1, 2). Second 2: stick 2 is larger, allocate 2 → (1, 0). Second 3: both have fewer than 3 bits, so it crashes. Answer is [3, 1, 0].

def mem_leak_crash(memory1, memory2):
    i = 1
    while i <= memory1 or i <= memory2:
        if memory1 >= memory2:
            memory1 -= i
        else:
            memory2 -= i
        i += 1
    return [i, memory1, memory2]
function memLeak(memory1, memory2) {
  let i = 1;
  while (i <= memory1 || i <= memory2) {
    if (memory1 >= memory2) {
      memory1 -= i;
    } else {
      memory2 -= i;
    }
    i += 1;
  }
  return [i, memory1, memory2];
}
class Solution {
    public int[] memLeak(int memory1, int memory2) {
        int i = 1;
        while (i <= memory1 || i <= memory2) {
            if (memory1 >= memory2) {
                memory1 -= i;
            } else {
                memory2 -= i;
            }
            i += 1;
        }
        return new int[]{ i, memory1, memory2 };
    }
}
vector<int> memLeak(int memory1, int memory2) {
    int i = 1;
    while (i <= memory1 || i <= memory2) {
        if (memory1 >= memory2) {
            memory1 -= i;
        } else {
            memory2 -= i;
        }
        i += 1;
    }
    return { i, memory1, memory2 };
}
Time: O(√(memory1 + memory2)) Space: O(1)