From 9576b18a61f373549b16a7103eea842b3f0e09ed Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Mon, 15 Mar 2021 21:57:25 -0700 Subject: [PATCH] Add another approach --- data_structures/arrays/remove_elements.rb | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/data_structures/arrays/remove_elements.rb b/data_structures/arrays/remove_elements.rb index 86d068e..44181d1 100644 --- a/data_structures/arrays/remove_elements.rb +++ b/data_structures/arrays/remove_elements.rb @@ -57,6 +57,31 @@ puts remove_elements([0,1,2,2,3,0,4,2], 2) # Approach 3: Two-pointers # +# Complexity analysis +# +# Time complexity: O(n). +# Assume the array has a total of n elements, +# both i and j traverse at most 2n steps. +# +# Space complexity: O(1). + +def remove_element(nums, val) + pointer1 = 0 + + nums.each_with_index do |num, pointer2| + if val != num + nums[pointer1] = nums[pointer2] + pointer1 += 1 + end + end + + pointer1 +end + +# +# Approach 4: Two-pointers (Optimized) +# + # Complexity analysis # # Time complexity: O(n). Both i and n traverse at most n steps.