Skip to content

Solution for question 27 #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions 0027/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# 27. Remove Elements

## Problem Statement

Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.

Return `k` after placing the final result in the first `k` slots of `nums`.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

## Link to problem

<https://leetcode.com/problems/remove-element/>
16 changes: 16 additions & 0 deletions 0027/RemoveElements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from typing import List


class Solution:

def removeElement(self, nums: List[int], val: int) -> int:
k = 0

for n in range(len(nums)):

# checks which element in the array does not match with val
if nums[n] != val:
nums[k] = nums[n]
k += 1 # increments the value of k by 1

return k