Delete an Element at a Position

Solve this Problem
Easy10 min
Topics
Companies
Given an array nums and a position index, return a new array with the element at that position removed. The elements after it move one place to the left. Deletion is the reverse of insertion: instead of opening a gap, the later elements shift leftShifting LeftMoving each element one position towards the front, overwriting the element being removed. to close one. The cost again depends on position — removing near the front moves almost everything, removing the last element moves nothing.

Test Case 1:

Input:nums = [4, 8, 15, 16], index = 1
Output:[4, 15, 16]
Explanation:8 is removed and the elements after it close the gap.

Test Case 2:

Input:nums = [9], index = 0
Output:[]
Explanation:Deleting the only element leaves an empty array.

Constraints

  • ◆1 ≤ nums.length ≤ 1000
  • ◆0 ≤ index < nums.length
  • ◆-1000000 ≤ nums[i] ≤ 1000000

Try the Dry Run

Approach & Solutions

Copy Everything Except the IndexGood

Make a new array one element shorter and copy across every element whose position is not index, keeping a separate write position j for the new array.

TimeO(n)
SpaceO(n)
class Solution { public int[] deleteAt(int[] nums, int index) { int[] result = new int[nums.length - 1]; int j = 0; for (int i = 0; i < nums.length; i++) { if (i != index) { result[j++] = nums[i]; } } return result; } }
Shift the Rest LeftOptimal

Work on a copy: starting at index, move each later element one place to the left, overwriting the deleted value. The last slot is then a leftover duplicate, so drop it. This is what delete operations on array-backed lists do internally.

TimeO(n)
SpaceO(n)
class Solution { public int[] deleteAt(int[] nums, int index) { int[] values = nums.clone(); for (int i = index; i < values.length - 1; i++) { values[i] = values[i + 1]; } return Arrays.copyOf(values, values.length - 1); } }

Related Problems