Remove Last K Elements

You are given an integer array arr of size N and an integer K. Your task is to remove the last K elements from the array and return the modified array.

Example 1:

Input:

nums = [5, 3, 8, 10]
K = 3

Output:

[5]

Explanation:

  • The array contains 4 elements. Removing the last 3 elements (3, 8, and 10) leaves only the first element.
  • Result: [5]

Example 2:

Input:

nums = [1, 2, 3]
K = 0

Output:

[1, 2, 3]

Explanation:

  • Since K = 0, no elements are removed from the end of the array.
  • Result: [1, 2, 3]

Now Your Turn!

Pick the correct output for the given input

Input:

nums = [4, 9, 2, 7, 5]
K = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= N <= 105
  • 0 <= K <= N
  • -105 <= nums[i] <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<int> removeKElements(vector<int>& nums, int k) {
// User code goes here
}
};
Test Case

Input:

K
Nums