Design a dynamic (resizable) array
Difficulty: 🔵 Basic
Techniques: DESIGN
Problem Statement
Design a Dynamic (resizable) Array class, such as an ArrayList
in Java or a vector
in C++
Your DynamicArray
class should support the following operations:
DynamicArray(int capacity)
will initialize an empty array with a capacity of capacity
, where capacity > 0
.
int get(int i)
will return the element at index i. Assume that index i is valid.
void set(int i, int n)
will set the element at index i to n. Assume that index i is valid.
void pushback(int n)
will push the element n to the end of the array.
int popback()
will pop and return the element at the end of the array. Assume that the array is non-empty.
void resize()
will double the capacity of the array.
int getSize()
will return the number of elements in the array.
int getCapacity()
will return the capacity of the array.
If we call pushback(int n)
but the array is full, we should resize the array first.
Solution
Also refer this GFG article: Implement your own Vector class