Queue Push Back
Given an array representing a queue and a new value, add (push/enqueue) the new value to the back of the queue and return the resulting array. The new element becomes the last in line.
For example, pushing 4 into [1, 2, 3] produces [1, 2, 3, 4]. Pushing 5 into an empty queue [] produces [5]. Pushing 0 into [1] produces [1, 0]. The operation always increases the queue size by exactly one.
The push (enqueue) operation is one of the two fundamental queue operations alongside pop (dequeue). Elements are added at the back and removed from the front, following the First-In-First-Out (FIFO) principle. This is the same behavior as a line at a store — new customers join at the back.
In array-based queue implementations, pushing is typically implemented by appending to the end of the array, which is O(1) amortized in most languages (the array may need to resize occasionally). In linked-list-based queues, a new node is created and linked at the tail, which is always O(1).
Edge cases include pushing into an empty queue (the result is a single-element array), pushing a negative value, and pushing multiple values sequentially (each push adds one element at the back).
Example Input & Output
Algorithm Flow
Solution Approach
Append the new value to the end of the array.
Create a copy of the input array to avoid mutation, then push the new value to the end. In languages without a copy-then-mutate pattern, you can use array concatenation: r = arr.concat([val]) in JavaScript, arr + [val] in Python, or append in Rust.
Time complexity is O(n) for the copy plus O(1) amortized for the push, or O(n) total. Space complexity is O(n) for the new array.
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] nums, int val) {
int[] r=Arrays.copyOf(nums,nums.length+1);
r[r.length-1]=val;
return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
