U

19. Dynamic Array with Fixed Initial Capacity

Easy

Problem Description

Implement a dynamic integer array from scratch using an initial buffer of capacity 4.

Support QQ operations:

  • •push x: Append integer xx to the end of array.
  • •get i: Print element at 0-based index ii. If ii is out of bounds, print -1.
  • •size: Print current number of elements.
  • •print: Print all elements space-separated, or EMPTY if empty.

Input Format

  • •Line 1: An integer QQ (1≤Q≤1041 \le Q \le 10^4).
  • •Next QQ lines: Operation commands.

Output Format

Print results for each get, size, and print operation on separate lines.

Example 1:
Input:
5
push 10
push 20
size
get 1
print
Output:
2
20
10 20
Explanation: Array contains 10 and 20. Size is 2. Element at index 1 is 20.
Example 2:
Input:
3
print
get 0
size
Output:
EMPTY
-1
0
Explanation: Empty array produces EMPTY, -1 for out-of-bounds get, and size 0.
Example 3:
Input:
6
push 5
push 15
push 25
get 2
get 3
size
Output:
25
-1
3
Explanation: Index 2 is 25, index 3 is out-of-bounds (-1), size is 3.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online