Code Logo

Queue Push Back

Published at25 Jul 2026
Basic Queue Easy 0 views
Like0

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

Example 1
Input
[1,2,3],4
Output
[1,2,3,4]
Example 2
Input
[10,20],30
Output
[10,20,30]
Example 3
Input
[1],2
Output
[1,2]
Example 4
Input
[],5
Output
[5]
Example 5
Input
([],[],[1,2,3])
Output
[1,2,3]

Algorithm Flow

Recommendation Algorithm Flow for Queue Push Back

Solution Approach

Append the new value to the end of the array.

function solution(arr, val) {
  var r = arr.slice();
  r.push(val);
  return r;
}

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

java
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;
    }
}