DEV Community

King coder
King coder

Posted on • Edited on

Day 24 and 25 of Learning DSA – Remove Duplicates, Remove Element, Sum of Natural Numbers, and Prime Number Checker

1. Remove Element

This solution removes all occurrences of a given value from an array in-place and returns the number of remaining elements. The relative order of the elements may be changed, and elements beyond the returned length are not guaranteed to be preserved.


🧠 Approach

  1. Create a variable x and initialize it to 0. This pointer will track the next position to place a valid element (i.e., not equal to val).
  2. Loop through the array using index j from 0 to nums.length - 1.
  3. If nums[j] !== val, it means the element should be kept:
    • Assign nums[j] to nums[x].
    • Increment x by 1.
  4. After the loop finishes, x will contain the number of elements that are not equal to val.
  5. Return x as the new length of the modified array.

🧮 Complexity

  • Time complexity:

    O(n) — We iterate through the array once.

  • Space complexity:

    O(1) — We do not use any additional space; all operations are in-place.


🧑‍💻 Code

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    let x = 0;
    for (let j = 0; j < nums.length; j++) {
        if (nums[j] !== val) {
            nums[x] = nums[j];
            x = x + 1;
        }
    }
    return x;
};

Enter fullscreen mode Exit fullscreen mode

2. Remove Duplicates from Sorted Array

This solution removes duplicates from a sorted array in-place and returns the number of unique elements.

🧠 Approach

  1. Create variable x and initialize it to 0.
  2. Loop through the array using a from 0 to arr.length - 1.
  3. Inside the loop, check if arr[x] < arr[a]:
    • If true, it means a new unique value is found.
  4. Increment x.
  5. Assign arr[a] to arr[x].
  6. After the loop, return x + 1 as the count of unique elements in the array.

This approach works because the input array is sorted, which means all duplicates are adjacent.

⏱ Time Complexity: O(n)

  • We go through the array only once from start to end.
  • Each check and update inside the loop takes the same small amount of time.
  • So the total time depends on how many items are in the array — that’s why it’s O(n).

🧠 Space Complexity: O(1)

  • We don’t use any extra space like another array.
  • We only use one variable (x) to help with tracking.
  • Because we use a fixed amount of memory, no matter how big the array is, the space used stays the same — that’s O(1).

Example Code

/**
 * @param {number[]} nums
 * @return {number}
 */

var removeDuplicates = function(nums) {
    let x = 0;
    for(let j = 0 ; j < nums.length ; j++){
      console.log(j)
        if(nums[x] < nums[j]){
            x = x + 1;
            nums[x] = nums[j]
        }
    }
    return x +1;
};
Enter fullscreen mode Exit fullscreen mode

🧮 Prime Number Checker

This program checks whether a given number is a prime number or not using basic iteration logic.


✅ What is a Prime Number?

A prime number is a number greater than 1 that is divisible only by 1 and itself.

Examples of prime numbers: 2, 3, 5, 7, 11, 13, ...


🚀 Approach

  1. Loop from i = 2 to i < num

    • We skip 1 because every number is divisible by 1.
    • We only check up to num - 1 to see if there's any divisor.
  2. Check if num % i === 0

    • If true, then num is divisible by i, so it's not a prime number.
  3. If num is divisible by any value other than 1 and itself

    • Return "num is not a prime number".
  4. If loop completes without finding a divisor

    • Return "num is a prime number".

⚠️ Edge Cases

  1. Number must be positive only

    • Negative numbers are not prime.
  2. Input must be a number, not a string

    • Type check is required.
  3. Number must be greater than 1

    • 0 and 1 are not prime numbers.

Example Usage

Input: 7
Output: 7 is a prime number

Input: 10
Output: 10 is not a prime number
Enter fullscreen mode Exit fullscreen mode

Example

JavaScript Code

function checkPrimeNumber(num) {
    let isPrime = true;

  if (typeof num !== 'number' || !Number.isInteger(num)) {
    return `${num} is not a valid input (must be an integer).`;
  }

  if (num <= 1) {
    return `${num} is not a prime number (must be greater than 1).`;
 }



    for (let i = 2; i < num; i++) {
        if (num % i === 0) {
            return `${num} is not a prime number`;
        }

    }

    return `${num} is a prime number`;





}


console.log(checkPrimeNumber(7)); 
console.log(checkPrimeNumber(10)); 



Enter fullscreen mode Exit fullscreen mode

Python Code

def checkPrimeNumber(num):
    if num <= 1:
        return f"{num} is not a valid input (must be an integer greater than 1)."
    if type(num) is not int:
        return f"{num} is not a valid input (must be an integer)."

    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return f"{num} is not a prime number."
    return f"{num} is a prime number."


print(checkPrimeNumber(11))  # Output: 11 is a prime number.
print(checkPrimeNumber(15))  # Output: 15 is not a prime number.

Enter fullscreen mode Exit fullscreen mode

Sum of Natural Numbers (Loop Approach)

This program calculates the sum of the first n natural numbers using a loop-based approach.


🚀 Approach

  1. Create a variable sum and initialize it to 0
  2. Use a loop to go from 1 to n
  3. In each iteration, add the current number to sum
  4. After the loop, return or print sum

#Example (n = 5)


Input: 5
Output: 15 (1 + 2 + 3 + 4 + 5)

Enter fullscreen mode Exit fullscreen mode

Time and Space Complexity

  • Time Complexity: O(n) --> Linear Search
  • Space Complexity: O(1) --> we use a Fix Space

Example

JavaScript Code

function Sum_Of_Natural_Numbers(n) {

if(n < 0 || typeof(n) !== "number") return 'Input must be a natural number greater than 0';

  let sum = 0;

   for(let i = 1 ; i <= n; i++) {

       sum += i;
   }
   return sum;
}

console.log(Sum_Of_Natural_Numbers(10)); // Output: 55
Enter fullscreen mode Exit fullscreen mode

Python Code

def Sum_Of_Natural_Numbers(n):
    # Corrected isinstance check and logic
    sum = 0
    if not isinstance(n, int) or n < 0:
        return f"{n} must be an integer and greater than or equal to 0"

    for i in range(1 , n + 1):
        sum += i


    return sum

# Updated test case with a valid integer input
print(Sum_Of_Natural_Numbers(10))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)