[Question]: Given an integer array nums
and an integer k
, remove all occurrences of k
in nums
in-place. The order of the elements may be changed. Then return the count after removal
Approach:
We can declare a variable which holds index initial it’s 0 now move elements which are not matched with k
// TC: O(n)
// SC: O(1)
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
var count = 0
for i in 0..<nums.count where nums[i] != val {
nums[count] = nums[i]
count+=1
}
return count
}
var arrOcc = [0,1,2,2,3,0,4,2]
removeElement(&arrOcc, 2)
//print("Output after removal --", arrOcc)//[0, 1, 3, 0, 4, 0, 4, 2]