Start learning free

LESSON 242 OF 671 · HELPER FUNCTIONS

Clamp the Values in Java: A Helper Method and a Loop

Practice Read the full explanation

You get an array of integers nums and two limits, low and high. Return every number moved inside the limits, in the same order.

A number below low becomes low. A number above high becomes high. Any other number stays as it is.

The work is split between two functions. The first one is a helper. It gets one number and the two limits. It returns that number moved inside them. The second one is the function that is graded. It calls the helper on every number.

Don't use a built-in min, max or clamp function. The helper does the comparing.

 

Example 1:

Input: nums = [12, -3, 7, 25], low = 0, high = 20
Output: [12, 0, 7, 20]
Explanation: -3 is below 0, so it becomes 0.
25 is above 20, so it becomes 20.
12 and 7 are already inside the limits.

Example 2:

Input: nums = [-8, -1, 4], low = -5, high = 5
Output: [-5, -1, 4]
Explanation: The limits can be negative too.
-8 is below -5, so it becomes -5.
-1 and 4 stay as they are.

Example 3:

Input: nums = [3, 9, 6], low = 6, high = 6
Output: [6, 6, 6]
Explanation: Both limits are 6, so every number becomes 6.

 

Constraints:

  • nums has at least one number.
  • Every number is between -1000 and 1000.
  • low and high are between -1000 and 1000.
  • low is never greater than high.
STEP 1 OF 7
    Ctrl + Enter to check

    JAVA · HELPER FUNCTIONS

    Clamp All in Java, explained

    Problem overview

    The method clampAll receives an array of integers nums and two limits, low and high. It returns a list with every number moved inside the limits, in the same order. A number below low becomes low. A number above high becomes high. Any other number stays as it is. The lesson asks you not to use a built-in min, max or clamp method.

    For nums = [12, -3, 7, 25], low = 0 and high = 20, the result is [12, 0, 7, 20]. The limits can be negative: with [-8, -1, 4] and the limits -5 and 5 the result is [-5, -1, 4]. When both limits are 6, every number becomes 6.

    Approach: split the work in two

    The lesson has two methods. The first, clamp, is a helper: it knows how to fix one number. The second, clampAll, loops over the array and calls the helper for each number. Each method does one small job, and neither needs to know how the other works. clampAll doesn't contain a single comparison, and clamp doesn't know about arrays.

    Step by step

    1. In clamp, if x is less than low, return low.
    2. Below that, if x is greater than high, return high.
    3. After the two if statements, return x. Only a number between the limits gets there, and it stays as it is. No else is needed, because a return ends the method.
    4. In clampAll, create an empty List<Integer> named clamped, an ArrayList.
    5. Loop over nums with an int named num.
    6. Inside the loop, add clamp(num, low, high) to clamped.
    7. After the loop, return clamped.

    The solution in Java

    class Solution {
        public int clamp(int x, int low, int high) {
            if (x < low) {
                return low;
            }
            if (x > high) {
                return high;
            }
            return x;
        }
    
        public List<Integer> clampAll(int[] nums, int low, int high) {
            List<Integer> clamped = new ArrayList<>();
            for (int num : nums) {
                clamped.add(clamp(num, low, high));
            }
            return clamped;
        }
    }

    A few Java details:

    • The input is an int[], an array of primitive ints, but the result is a List<Integer>. A list can't hold primitives, so Java boxes each int into an Integer when you call add.
    • Inside the class, clampAll calls clamp by its plain name. Both are methods of the same Solution object.
    • The two if statements are separate, not an if/else if chain. That is safe, because the lesson promises low is never greater than high, so a number can't be both below low and above high.

    Following the first example

    With nums = [12, -3, 7, 25], low = 0 and high = 20, the loop calls the helper four times:

    • clamp(12, 0, 20): 12 is not below 0 and not above 20, so the helper reaches the last line and returns 12.
    • clamp(-3, 0, 20): -3 is below 0, so the first if returns 0.
    • clamp(7, 0, 20): inside the limits, so 7.
    • clamp(25, 0, 20): 25 is above 20, so the second if returns 20.

    The list grows by one number per turn, in the order of the array, and ends as [12, 0, 7, 20].

    Why a helper is worth it

    You could write both comparisons inside the loop and skip the second method. It would work, but the helper has two advantages. First, you can test it alone: call clamp on a few numbers and see whether it behaves, before the loop is involved. Second, the loop stays easy to read. clamped.add(clamp(num, low, high)) says what it does in a single line, and if the rule for moving a number ever changes, only the helper changes.

    Edge cases and common mistakes

    • Equal limits. With low == high every number ends up at that value, as in the third example.
    • Numbers exactly on a limit. They are not less than low or greater than high, so they stay. Using <= or >= would still return the same value here, but the strict comparisons say what is meant.
    • Swapping the limits. Returning high for the low check, or the reverse, makes every out-of-range number jump to the wrong side.
    • Returning inside the loop. The return goes after the loop; inside it only one number would come back.

    The input stays untouched

    The method builds a new list and does not write into nums. That is the safer habit: the caller still has the original numbers, and a mistake in the loop can't damage them. It also explains the types. The array can't change size, and the lesson asks for a list back, so the loop collects the answers one by one with add, and the list grows to the right size by itself.

    Because the helper takes plain int parameters, it works on any single number, and the loop passes the same low and high to every call. The limits never change during the loop.

    Reading the result

    If the result looks wrong, check the helper first. A number that should have moved but didn't points to a comparison that is the wrong way round. A number that moved to the wrong limit points to swapped return values. If the helper is right and the list is still wrong, the problem is in the loop, for example a missing add or an early return.

    Testing

    Running the solution on the three examples gives:

    [12, 0, 7, 20]
    [-5, -1, 4]
    [6, 6, 6]

    Calling clamp alone on -3, 25 and 12 with the limits 0 and 20 gives 0, 20 and 12.

    Keep going with Java500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free