문제
A dynamic array such as C++ std::vector stores its elements in one block of memory. When the block is full and a new element arrives, it allocates a block twice as large, copies the existing elements over, and frees the old one.
Start with an empty array of capacity initial_capacity and push pushes elements one by one. Before each push, if size == capacity, reallocate: count one reallocation, add the current size to the copied elements, and double the capacity.
Implement dynamic_array_growth(pushes, initial_capacity).
Input
pushes: How many elements are pushed.
initial_capacity: The capacity of the empty array.
Output
Return [reallocations, copied_elements, final_capacity].
제약 조건
0 ≤ pushes ≤ 10^7
1 ≤ initial_capacity ≤ 10^6
예시
입력:
pushes = 5
initial_capacity = 1
예상 출력:
expected = [3, 7, 8]
입력:
long long pushes = 5;
long long initial_capacity = 1;
예상 출력:
std::vector<long long> expected = {3, 7, 8};
입력:
long pushes = 5;
long initial_capacity = 1;
예상 출력:
long[] expected = new long[] {3, 7, 8};
설명
Capacity grows 1 → 2 → 4 → 8 when pushing the 2nd, 3rd and 5th elements, copying 1 + 2 + 4 = 7 elements: [3, 7, 8].
입력:
pushes = 4
initial_capacity = 4
예상 출력:
expected = [0, 0, 4]
입력:
long long pushes = 4;
long long initial_capacity = 4;
예상 출력:
std::vector<long long> expected = {0, 0, 4};
입력:
long pushes = 4;
long initial_capacity = 4;
예상 출력:
long[] expected = new long[] {0, 0, 4};
설명
All four elements fit in the first block, so nothing is reallocated: [0, 0, 4].
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
A reallocation happens only when the array is full.
힌트 2
Each time, all current elements are copied and the capacity doubles.
힌트 3
You can jump from one doubling to the next instead of simulating every push.
예상 복잡도
O(log pushes) time, O(1) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.