Tutte le sfide
Facile 0 risolte 0% di accettazione

Growing a Dynamic Array

Simulate how a dynamic array doubles its capacity and count the reallocations and copied elements.

Cosa imparerai

  • See how a vector doubles its capacity
  • Count copies made during reallocation
  • Understand why appending stays fast on average

Problema

Mostra traduzione

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].

Vincoli

0 ≤ pushes ≤ 10^7

1 ≤ initial_capacity ≤ 10^6

Esempi

Esempio 1
Input:
pushes = 5
initial_capacity = 1

Output atteso:
expected = [3, 7, 8]
Input:
long long pushes = 5;
long long initial_capacity = 1;

Output atteso:
std::vector<long long> expected = {3, 7, 8};
Input:
long pushes = 5;
long initial_capacity = 1;

Output atteso:
long[] expected = new long[] {3, 7, 8};

Spiegazione

Capacity grows 1 → 2 → 4 → 8 when pushing the 2nd, 3rd and 5th elements, copying 1 + 2 + 4 = 7 elements: [3, 7, 8].

Esempio 2
Input:
pushes = 4
initial_capacity = 4

Output atteso:
expected = [0, 0, 4]
Input:
long long pushes = 4;
long long initial_capacity = 4;

Output atteso:
std::vector<long long> expected = {0, 0, 4};
Input:
long pushes = 4;
long initial_capacity = 4;

Output atteso:
long[] expected = new long[] {0, 0, 4};

Spiegazione

All four elements fit in the first block, so nothing is reallocated: [0, 0, 4].

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

A reallocation happens only when the array is full.

Suggerimento 2

Each time, all current elements are copied and the capacity doubles.

Suggerimento 3

You can jump from one doubling to the next instead of simulating every push.

Complessità attesa

O(log pushes) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.