Bird
Raised Fist0
DSA C++programming~10 mins

Dynamic Stack Using Resizable Array in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Dynamic Stack Using Resizable Array
Start
↓
Push Element
↓
Check Capacity Full?
No→Add Element at Top
Yes↓
Double Array Size
↓
Copy Old Elements
↓
Add Element at Top
↓
Update Top Index
↓
Done
↓
Pop Element
↓
Check Stack Empty?
Yes→Error or Return Null
No↓
Remove Element at Top
↓
Update Top Index
↓
Check Capacity Too Large?
No→Done
Yes↓
Halve Array Size
↓
Copy Elements to Smaller Array
↓
Done
The stack adds elements at the top, resizing the array by doubling when full, and removes elements from the top, halving the array size when too empty.
Execution Sample
DSA C++
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
stack.push(40);
Push three elements, pop one, then push another, showing dynamic resizing and stack state changes.
Execution Table
StepOperationArray CapacityTop IndexPointer ChangesVisual State
1push(10)20Add 10 at index 0[10, _]
2push(20)21Add 20 at index 1[10, 20]
3push(30)42Capacity full, double size to 4; copy [10,20]; add 30 at index 2[10, 20, 30, _]
4pop()41Remove element at index 2 (30)[10, 20, _, _]
5push(40)42Add 40 at index 2[10, 20, 40, _]
💡 Execution stops after 5 operations; stack has 3 elements with capacity 4.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5
Array Capacity222444
Top Index-101212
Stack Elements[][10][10, 20][10, 20, 30][10, 20][10, 20, 40]
Key Moments - 3 Insights
Why does the array capacity double at step 3?
At step 3, the array is full (capacity 2, top index 1). To add a new element, the array size doubles to 4 to have space, as shown in execution_table row 3.
Why does the top index decrease after pop at step 4?
Pop removes the top element (index 2), so top index moves from 2 to 1, indicating the new top is at index 1, as shown in execution_table row 4.
Does the array size shrink after popping at step 4?
No, the capacity remains 4 after pop at step 4 because the stack is not less than half full, so no shrinking occurs, as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the array capacity after step 3?
A2
B3
C4
D5
💡 Hint
Check the 'Array Capacity' column at step 3 in execution_table.
At which step does the top index become 1?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Top Index' column in variable_tracker after each step.
If we push one more element after step 5, what will happen to the array capacity?
AIt will double from 4 to 8
BIt will stay at 4
CIt will halve to 2
DIt will increase by 1
💡 Hint
At step 5, capacity is 4 and top index is 2; pushing one more element fits without resizing.
Concept Snapshot
Dynamic Stack Using Resizable Array:
- Push adds element at top index +1.
- If array full, double capacity and copy elements.
- Pop removes element at top index and decrements top.
- If usage low, optionally halve capacity.
- Top index starts at -1 (empty stack).
- Array capacity changes dynamically to save space.
Full Transcript
This visual trace shows how a dynamic stack uses a resizable array. When pushing, if the array is full, it doubles in size and copies old elements before adding the new one. Popping removes the top element and moves the top index down. The array capacity does not shrink unless usage is low. The top index tracks the current top element position, starting at -1 when empty. This example pushes 10, 20, 30, pops once, then pushes 40, showing capacity doubling and stack state changes.

Practice

(1/5)
1. What is the main advantage of using a dynamic stack implemented with a resizable array compared to a fixed-size array stack?
easy
A. It can grow or shrink automatically as elements are pushed or popped.
B. It uses less memory than a linked list stack.
C. It always has a fixed maximum size.
D. It does not require resizing when full.

Solution

  1. Step 1: Understand fixed vs dynamic size

    A fixed-size array stack has a set capacity and cannot grow beyond it, causing overflow if exceeded.
  2. Step 2: Explain dynamic resizing

    A dynamic stack using a resizable array automatically increases or decreases its size when needed, avoiding overflow and wasted space.
  3. Final Answer:

    It can grow or shrink automatically as elements are pushed or popped. -> Option A
  4. Quick Check:

    Dynamic resizing = automatic growth/shrink [OK]
Hint: Dynamic arrays resize automatically to fit elements [OK]
Common Mistakes:
  • Thinking dynamic stack has fixed size
  • Confusing memory use with linked list
  • Assuming no resizing needed
2. Which of the following is the correct syntax to double the size of the array when the stack is full in C++?
easy
A. arr = new int[size * 2];
B. arr.resize(size * 2);
C. arr = (int*) realloc(arr, size * 2 * sizeof(int));
D. arr = arr * 2;

Solution

  1. Step 1: Identify array resizing in C++

    For raw arrays, realloc is used to resize memory blocks dynamically.
  2. Step 2: Check each option

    arr = new int[size * 2]; creates a new array but loses old data. arr.resize(size * 2); is for std::vector, not raw arrays. arr = (int*) realloc(arr, size * 2 * sizeof(int)); correctly uses realloc to resize preserving data. arr = arr * 2; is invalid syntax.
  3. Final Answer:

    arr = (int*) realloc(arr, size * 2 * sizeof(int)); -> Option C
  4. Quick Check:

    Raw array resize = realloc [OK]
Hint: Use realloc for raw array resizing in C++ [OK]
Common Mistakes:
  • Using vector methods on raw arrays
  • Creating new array without copying data
  • Invalid pointer arithmetic
3. Consider the following C++ code snippet for a dynamic stack push operation:
void push(int x) {
  if (top == capacity) {
    capacity *= 2;
    arr = (int*) realloc(arr, capacity * sizeof(int));
  }
  arr[top++] = x;
}

// Initial capacity = 2, top = 0
push(10);
push(20);
push(30);
What is the value of capacity and the stack elements after these pushes?
medium
A. capacity = 2, stack = [10, 20, 30]
B. capacity = 4, stack = [10, 20, 30]
C. capacity = 3, stack = [10, 20, 30]
D. capacity = 4, stack = [10, 20]

Solution

  1. Step 1: Trace push calls and capacity changes

    Initial capacity is 2. After pushing 10 and 20, top reaches 2 (full). On pushing 30, capacity doubles to 4, and 30 is added.
  2. Step 2: Confirm final stack and capacity

    Stack elements are [10, 20, 30], capacity is 4 after resizing.
  3. Final Answer:

    capacity = 4, stack = [10, 20, 30] -> Option B
  4. Quick Check:

    Capacity doubles when full, stack holds all pushed elements [OK]
Hint: Capacity doubles only when full before push [OK]
Common Mistakes:
  • Not doubling capacity before adding new element
  • Assuming capacity equals number of elements
  • Ignoring realloc effect
4. The following code snippet for pop operation in a dynamic stack has a bug:
int pop() {
  if (top == 0) {
    throw "Stack Underflow";
  }
  int val = arr[--top];
  if (top < capacity / 4) {
    capacity /= 2;
    arr = (int*) realloc(arr, capacity * sizeof(int));
  }
  return val;
}
What is the bug and how to fix it?
medium
A. Bug: throw uses string literal; Fix: use std::exception instead.
B. Bug: pop does not decrease top; Fix: decrement top before accessing.
C. Bug: capacity can become zero; Fix: ensure capacity never goes below 1.
D. Bug: realloc is called without checking NULL; Fix: check realloc return.

Solution

  1. Step 1: Analyze realloc usage

    realloc can fail to allocate memory and return NULL, but the code does not check the return value before using arr, which can lead to crashes.
  2. Step 2: Fix by checking realloc return

    Store the result in a temporary pointer and check if it is NULL before assigning to arr. Handle the error case appropriately.
  3. Final Answer:

    Bug: realloc is called without checking NULL; Fix: check realloc return. -> Option D
  4. Quick Check:

    Always check realloc != NULL [OK]
Hint: Always check realloc return for NULL [OK]
Common Mistakes:
  • Ignoring minimum capacity limit
  • Not decrementing top before access
  • Not checking realloc NULL
5. You want to implement a dynamic stack using a resizable array that shrinks its capacity when the number of elements falls below one-fourth of the capacity, but never shrinks below an initial capacity of 4. Which of the following code snippets correctly implements the pop operation with this behavior?
int pop() {
  if (top == 0) throw "Underflow";
  int val = arr[--top];
  if (top < capacity / 4 && capacity > 4) {
    capacity /= 2;
    arr = (int*) realloc(arr, capacity * sizeof(int));
  }
  return val;
}
What is the key reason for checking capacity > 4 before resizing?
hard
A. To prevent the capacity from shrinking below the initial minimum size, avoiding invalid memory access.
B. To ensure the stack always has space for at least four elements, improving performance.
C. To avoid calling realloc too frequently, which slows down the program.
D. To keep the capacity as a power of two for easier indexing.

Solution

  1. Step 1: Understand capacity shrinking condition

    The stack shrinks when elements are less than one-fourth capacity, but must not shrink below initial capacity 4.
  2. Step 2: Explain importance of capacity > 4 check

    This check prevents capacity from becoming less than 4, which avoids invalid memory allocation and potential errors.
  3. Final Answer:

    To prevent the capacity from shrinking below the initial minimum size, avoiding invalid memory access. -> Option A
  4. Quick Check:

    Minimum capacity check prevents invalid resize [OK]
Hint: Check minimum capacity before shrinking array [OK]
Common Mistakes:
  • Shrinking capacity below initial size
  • Ignoring memory safety on realloc
  • Assuming performance reason only
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard