I4G10DaysOfCodeChallenge: Thought process behind the "Remove Element" leetcode problem,

Let's start with defining the problem statement for today's challenge.

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. Return k after placing the final result in the first k slots of nums.

This low-key looks like a sorting problem, no wonder my inspiration for a suitable algorithm comes from the popular bubble sort algorithm.

According to Wikipedia, Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the input list element by element, comparing the current element with the one after it, swapping their values if needed. These passes through the list are repeated until no swaps had to be performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a comparison sort, is named for the way the larger elements "bubble" up to the top of the list.

In the same way, my approach to this problem was to modify the bubble sort algorithm, instead of bubbling the larger elements to the top I bubbled non-val elements to the top. I also kept track of each bubble I performed (in a variable k) to get the length of the non-val elements.

Implementation:

1) The code started with initializing k to 0 2) Initialized a for loop to loop through the array. 3) For each iteration, used an if statement to determine if the element was a non-val element 4) if it is determined to be, it would be bubbled to the first position by setting nums[k] = nums[i] 5) By the end of the loop, the last non-val element is bubbled to the kth position and K is returned as required

Unlike the bubble sort , this algorithm has a better time complexity of O(n) and a space complexity of O(1).