Incremental Memory Leak - 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.

At the i-th second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.

Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.

Input & Output

Example 1 — Basic Case
$ Input: memory1 = 2, memory2 = 2
Output: [3,1,0]
💡 Note: Second 1: allocate 1 bit to memory1 (both equal, choose first) → [1,2]. Second 2: allocate 2 bits to memory2 (2 > 1) → [1,0]. Second 3: need 3 bits but memory1 has only 1, memory2 has 0 → crash at second 3 with remaining [1,0]
Example 2 — Unequal Memory
$ Input: memory1 = 8, memory2 = 11
Output: [6,0,4]
💡 Note: Allocation sequence: [8,11] → [7,11] → [7,9] → [4,9] → [4,5] → [4,0] → crash at second 6 when need 6 bits but max available is 4
Example 3 — Single Large Memory
$ Input: memory1 = 1, memory2 = 8
Output: [4,0,6]
💡 Note: Second 1: [0,8], Second 2: [0,6], Second 3: [0,3], Second 4 needs 4 bits but only 3 available → crash

Constraints

  • 0 ≤ memory1, memory2 ≤ 231 - 1

Visualization

Tap to expand
Incremental Memory Leak INPUT Two Memory Sticks Memory 1 2 bits Memory 2 2 bits Input Values: memory1 = 2 memory2 = 2 Allocation Rule: At second i, allocate i bits to stick with MORE memory (or stick 1 if equal) ALGORITHM STEPS 1 Second 1: Allocate 1 bit m1=m2, use m1: 2-1=1 m1:1 m2:2 2 Second 2: Allocate 2 bits m2 > m1, use m2: 2-2=0 m1:1 m2:0 3 Second 3: Need 3 bits m1=1, m2=0: Neither enough! CRASH! 4 Record Crash State time=3, m1=1, m2=0 Memory Timeline t=1 t=2 t=3 X m1 m2 FINAL RESULT Program Crashed at Second 3 3 Crash Time Memory 1 1 Memory 2 0 Output Array: 3 1 0 [3, 1, 0] OK - Verified Correct Key Insight: Mathematical Optimization The crash time follows the triangular number formula: 1+2+3+...+n = n(n+1)/2. The program crashes when total memory (m1+m2) cannot accommodate the next allocation. With m1=2, m2=2 (total=4), after t=2 we've used 1+2=3 bits. At t=3, we need 3 more bits but only have 1 remaining, causing the crash. TutorialsPoint - Incremental Memory Leak | Mathematical Optimization Approach
Asked in
Amazon 15 Microsoft 12 Google 8
23.4K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen