703387. Smallest Non-Zero Number

Medium

Find Smallest Non-Zero Number

Summary

The problem involves finding the smallest non-zero number in a given array. This is a classic algorithmic problem that requires understanding of basic programming concepts and data structures.

Detailed Explanation

The problem can be solved by iterating through the array, keeping track of the smallest non-zero number encountered so far. Here's a step-by-step breakdown of the solution:

  1. Initialize a variable smallest to store the smallest non-zero number.
  2. Iterate through the array:
    • For each element in the array, check if it is not zero (if (element != 0)).
    • If the element is not zero and smaller than the current smallest, update smallest.
  3. After iterating through the entire array, smallest will hold the smallest non-zero number found.

Here's a diagram illustrating the process:

          +---------------+
          |       Array    |
          +---------------+
                  |
                  v
+---------------------+
|  Iterate through   |
|  elements and find  |
|  smallest non-zero   |
+---------------------+
          |
          v
+---------------------+
|  Return smallest    |
|  non-zero number    |
+---------------------+

The time complexity of this algorithm is O(n), where n is the length of the array, since we need to iterate through each element once. The space complexity is O(1), as we only use a constant amount of space to store the smallest variable.

Optimized Solutions

Java

View on GeeksforGeeks
public int findSmallestNonZeroNumber(int[] arr) {
    int smallest = Integer.MAX_VALUE;
    for (int element : arr) {
        if (element != 0 && element < smallest) {
            smallest = element;
        }
    }
    return smallest;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.