DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #27. Remove Element

Time Complexity O(n)

Breaking it down:

Single for loop: Iterates through the entire array once, from index 0 to nums.length - 1
Inside the loop:

Comparison nums[i] == val: O(1)
Assignment nums[index] = nums[i]: O(1)
Increment operations: O(1)

Since we visit each element exactly once and perform constant-time operations, the total time complexity is O(n) where n = nums.length.

Space Complexity O(1)

Variables used: index, k, i - all use constant space
No additional data structures: No extra arrays, lists, or collections created
In-place modification: The algorithm modifies the input array directly without using additional space proportional to input size

Total auxiliary space: O(1) (constant space)

class Solution {
    public int removeElement(int[] nums, int val) {
        int index = 0;
        int k = 0;

        for (int i = 0; i< nums.length; i++) {
            if(nums[i] == val) {
                continue;
            } else {
                nums[index] = nums[i];
                index++;
                k++;
            }
        }
        return k;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)