forked from simranlotey/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecondSmallest.ts
33 lines (27 loc) · 867 Bytes
/
secondSmallest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function findSecondSmallest(arr: number[]): number | null {
if (arr.length < 2) {
console.error("The array should contain at least two numbers.");
return null;
}
let smallest = Infinity;
let secondSmallest = Infinity;
for (let num of arr) {
if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num !== smallest) {
secondSmallest = num;
}
}
if (secondSmallest === Infinity) {
console.error("There is no second smallest number in the array.");
return null;
}
return secondSmallest;
}
// Example usage
const array = [5, 3, 8, 1, 9, 2, 4];
const secondSmallest = findSecondSmallest(array);
if (secondSmallest !== null) {
console.log("The second smallest number is:", secondSmallest);
}