
Problem
Solution
Submissions
Second Smallest Number in an Array
Certification: Basic Level
Accuracy: 20%
Submissions: 10
Points: 5
Write a C# program to implement the FindSecondSmallest(int[] nums) function, which finds the second smallest element in an array of integers. If the array contains duplicate elements, they should be considered as separate elements.
Algorithm
- Step 1: Check if the array has at least 2 elements. If not, return an appropriate value or throw an exception.
- Step 2: Find the smallest element in the array.
- Step 3: Find the smallest element in the array that is greater than the smallest element found in step 2.
- Step 4: Return the second smallest element.
Example 1
- Input: nums = [5, 2, 8, 1, 9]
- Output: 2
- Explanation:
- The smallest element is 1.
- The second smallest element is 2.
Example 2
- Input: nums = [7, 7, 7, 7]
- Output: 7
- Explanation:
- All elements are the same, so the smallest and second smallest are both 7.
Constraints
- 2 ≤ nums.length ≤ 10^5
- -2^31 ≤ nums[i] ≤ 2^31 - 1
- The array will contain at least 2 elements.
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- You can solve this in a single pass through the array by maintaining two variables.
- Be careful with edge cases like all elements being the same.
- Handle the case where the smallest element appears multiple times.
- Consider what should happen if the array has less than 2 elements.