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
-
Create a variable
x
and initialize it to0
. This pointer will track the next position to place a valid element (i.e., not equal toval
). -
Loop through the array using index
j
from0
tonums.length - 1
. -
If
nums[j] !== val
, it means the element should be kept:- Assign
nums[j]
tonums[x]
. - Increment
x
by1
.
- Assign
- After the loop finishes,
x
will contain the number of elements that are not equal toval
. - 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;
};
2. Remove Duplicates from Sorted Array
This solution removes duplicates from a sorted array in-place and returns the number of unique elements.
🧠 Approach
- Create variable
x
and initialize it to0
. - Loop through the array using
a
from0
toarr.length - 1
. - Inside the loop, check if
arr[x] < arr[a]
:- If true, it means a new unique value is found.
- Increment
x
. - Assign
arr[a]
toarr[x]
. - 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;
};
🧮 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
-
Loop from
i = 2
toi < 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.
- We skip
-
Check if
num % i === 0
- If true, then
num
is divisible byi
, so it's not a prime number.
- If true, then
-
If num is divisible by any value other than 1 and itself
- Return
"num is not a prime number"
.
- Return
-
If loop completes without finding a divisor
- Return
"num is a prime number"
.
- Return
⚠️ Edge Cases
-
Number must be positive only
- Negative numbers are not prime.
-
Input must be a number, not a string
- Type check is required.
-
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
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));
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.
Sum of Natural Numbers (Loop Approach)
This program calculates the sum of the first n
natural numbers using a loop-based approach.
🚀 Approach
- Create a variable
sum
and initialize it to 0 - Use a loop to go from 1 to
n
- In each iteration, add the current number to
sum
- After the loop, return or print
sum
#Example (n = 5)
Input: 5
Output: 15 (1 + 2 + 3 + 4 + 5)
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
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))
Top comments (0)