866. Design Array Modifier
Design a class ArrayModifier to simulate a dynamic array that supports inserting elements at the beginning, end, or a specific position.
Implement the following methods:
- ArrayModifier(int[] nums): Initializes the array with given integers.
- insertAtBeginning(int val): Inserts val at the beginning of the array.
- insertAtEnd(int val): Inserts val at the end of the array.
- insertAtPosition(int val, int pos): Inserts val at position pos (1-indexed).
Example 1:
Input: calls = ["ArrayModifier", "insertAtBeginning", "insertAtEnd", "insertAtPosition"], params = [[1,2,3,4,5], [6], [7], [8, 4]]
Output: [null, [6,1,2,3,4,5], [6,1,2,3,4,5,7], [6,1,2,8,3,4,5,7]]
Explanation:
- Array starts as [1,2,3,4,5]
- Insert 6 at the beginning → [6,1,2,3,4,5]
- Insert 7 at the end → [6,1,2,3,4,5,7]
- Insert 8 at position 4 → [6,1,2,8,3,4,5,7]
Example 2:
Input: calls = ["ArrayModifier", "insertAtEnd", "insertAtBeginning", "insertAtPosition"], params = [[], [10], [5], [7, 2]]
Output: [null, [10], [5,10], [5,7,10]]
Explanation:
- Starts empty
- Insert 10 at end → [10]
- Insert 5 at beginning → [5,10]
- Insert 7 at position 2 → [5,7,10]
Now Your Turn!
Pick the correct output for the given inputWhat will be Final Array after performing following operations ?
Input: calls = ["ArrayModifier", "insertAtEnd", "insertAtBeginning", "insertAtPosition"], params = [[3, 4], [5], [2], [6, 3]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 0 ≤ nums.length ≤ 10⁴
- 1 ≤ val ≤ 10⁶
- 1 ≤ pos ≤ current array size + 1