Bird
Raised Fist0
DSA C++programming~5 mins

Dynamic Stack Using Resizable Array in DSA C++ - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Dynamic Stack Using Resizable Array
O(1) amortized
Understanding Time Complexity

We want to understand how the time to add or remove items from a dynamic stack changes as the stack grows.

How does resizing the array affect the speed of stack operations?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class DynamicStack {
  int* arr;
  int capacity;
  int topIndex;

  void resize() {
    int* newArr = new int[capacity * 2];
    for (int i = 0; i < capacity; i++) {
      newArr[i] = arr[i];
    }
    capacity *= 2;
    delete[] arr;
    arr = newArr;
  }

  void push(int val) {
    if (topIndex == capacity) resize();
    arr[topIndex++] = val;
  }

  int pop() {
    return arr[--topIndex];
  }
};
    

This code shows a stack that doubles its array size when full, allowing dynamic growth.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Pushing items and occasionally resizing the array.
  • How many times: Each push usually adds one item; resizing happens less often but copies all current items.
How Execution Grows With Input

Most pushes take a simple step, but when the array is full, resizing copies all items, which takes longer.

Input Size (n)Approx. Operations
10About 10 simple pushes, 1 resize copying 10 items
100About 100 pushes, 3 resizes copying 10, 20, 40 items
1000About 1000 pushes, 7 resizes copying 10, 20, 40, 80, 160, 320, 640 items

Pattern observation: Resizing happens rarely and copies all items, but most pushes are quick, so average work per push stays low.

Final Time Complexity

Time Complexity: O(1) amortized

This means each push usually takes a quick step, and resizing cost spreads out over many pushes, keeping average time per push constant.

Common Mistake

[X] Wrong: "Every push takes a long time because resizing copies all items."

[OK] Correct: Resizing happens only occasionally, so most pushes are fast. The copying cost is shared across many pushes, making average time low.

Interview Connect

Understanding amortized time helps you explain why dynamic arrays and stacks are efficient in real programs, showing you grasp practical performance.

Self-Check

"What if we increased the array size by only 1 each time instead of doubling? How would the time complexity change?"

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