DEV Community

Cover image for Remove Element - Leetcode 27 - TypeScript
Yaz
Yaz

Posted on • Updated on

Remove Element - Leetcode 27 - TypeScript

Here's the Leetcode 27 solution using TypeScript.

Watch on Youtube

Leetcode 27 - Remove Element:

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

  • Return k.

Approach

Your goal is to remove all occurrences of a specified value from an array nums and return the new length of the modified array.

You can use two pointers: one i to iterate through the original array and another k to keep track of the position where non-matching elements should be placed.

You'll loop through each element in the array, and if the current element is not equal to the target value, it means you want to keep that element.

In this case, we assign the value of the current element to the position indicated by the pointer k and then increment k.

This effectively removes the occurrences of val from the modified portion of the array.

Then you'll have your modified array, and you can also return k which is basically the length of the modified array.

Image description
View on Excalidraw

Code Implementation

function removeElement(nums: number[], val: number): number {
  let k = 0

  for (let i = 0; i < nums.length; i++) {
    const element = nums[i]
    if (nums[i] !== val) {
      nums[k] = nums[i]
      k++
    }
  }

  return k
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input array nums.

This is because the algorithm iterates through each element in the array once, and the operations inside the loop take constant time.

Space Complexity

The space complexity is O(1) or constant because the algorithm modifies the input array in-place,and we are using only a constant amount of extra space for variables. It doesn't require additional memory that scales with the size of the input array.

In simpler terms, the time it takes to run the algorithm grows linearly with the size of the input array, and it doesn't use much extra memory regardless of the array's size.

Top comments (0)