Start learning free

LESSON 245 OF 674 · HELPER FUNCTIONS

Clamp the Values in C#: 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

    C# · HELPER FUNCTIONS

    Clamp All in C#, explained

    Problem overview

    You get an int[] named nums and two limits, low and high. ClampAll returns every number moved inside the limits, in the same order, as a List<int>. A number below low becomes low, a number above high becomes high, and any other number stays.

    For nums = [12, -3, 7, 25], low = 0 and high = 20, the answer is [12, 0, 7, 20]: -3 moves up to 0, 25 moves down to 20, and 12 and 7 are already inside. The limits can be negative: with [-8, -1, 4] and limits -5 and 5 the answer is [-5, -1, 4]. When both limits are 6, as in [3, 9, 6], every number becomes 6.

    Approach: split the work in two

    The lesson has two methods. Clamp is a helper: it deals with one number and knows nothing about arrays. ClampAll only loops, and asks the helper about each number. Splitting the work this way means each method does one small job. The helper's rules (below, above, or inside) are written once, and the loop stays free of if statements.

    The helper needs no else. If the number is below low, the method returns right there. If it is above high, it returns there. Whatever reaches the last line is between the limits and is returned unchanged.

    Step by step

    1. In Clamp, test x < low and return low.
    2. Test x > high and return high.
    3. Return x after the two if statements.
    4. In ClampAll, create an empty List<int> named clamped. The input is an array, whose size is fixed, but the answer is built one value at a time, which a list does well.
    5. Loop over nums with foreach (int num in nums). There is exactly one result per input number.
    6. Add Clamp(num, low, high) to clamped.
    7. Return clamped after the loop.

    The solution in C#

    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<int> ClampAll(int[] nums, int low, int high) {
            List<int> clamped = new List<int>();
            foreach (int num in nums) {
                clamped.Add(Clamp(num, low, high));
            }
            return clamped;
        }
    }
    

    The details worth knowing:

    • One method of a class can call another by name: ClampAll calls Clamp with no prefix.
    • The input is an int[] and the output is a List<int>. They are different types, so you build a new collection instead of changing the array in place.
    • .NET has Math.Clamp, which does the same job as the helper. The lesson asks you to write the comparing yourself, so the exercise doesn't use it.

    Why a helper is worth it

    You could write the three-way decision inside the loop of ClampAll. It would work, but that loop would then do two jobs at once: walk the array and decide what happens to a single number. With a helper, each job has a name. When a result looks wrong, you can test Clamp on its own with one number and one pair of limits, without building an array first. Once the helper is trusted, the loop is easy to read: for every number, add the clamped number.

    Helpers also pay off when a rule is needed in more than one place. If another method later had to clamp a single score, it could call Clamp directly instead of copying the comparisons.

    Tracing the first example

    With limits 0 and 20, the helper answers like this for each number of [12, -3, 7, 25]:

    Clamp(12, 0, 20) = 12
    Clamp(-3, 0, 20) = 0
    Clamp(7, 0, 20) = 7
    Clamp(25, 0, 20) = 20
    

    Notice that the first and third calls return the number they were given, because those numbers are already between the limits. When both limits are 6, as in the third example, the first test catches every number below 6, the second catches every number above 6, and a 6 passes through both tests and is returned as it is. So every number ends up as 6.

    Testing

    On the statement's three examples, the method returns:

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

    Edge cases and common mistakes

    • Swapped limits. The constraints say low is never greater than high, so the helper doesn't need to handle the other order.
    • Returning inside the loop. A return there ends ClampAll after the first number. Return after the loop.
    • Forgetting to use the result. Calling Clamp(num, low, high); alone changes nothing, because the helper returns a new value and does not modify num. The value has to be added to the list.
    • Writing both comparisons with <=. A number equal to a limit would still be returned correctly, but the strict comparisons say exactly what the rule is.

    Checking your own version

    A good habit is to test the helper by itself before the loop. Try a number below the lower limit, one above the upper limit, one in the middle, and one exactly equal to each limit. Those cases cover every path through Clamp. Then run the full method on an array that mixes them, and compare the list you get with the expected list value by value. If the values are right but the order is wrong, check that you add to the list inside the loop and not after it.

    Remember too that the result is a new list. The original array nums is left as it was, which matters if the caller still needs the unclamped numbers.

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