Start learning free

LESSON 241 OF 667 · HELPER FUNCTIONS

Clamp the Values in C++: A Helper Function in a Loop

Practice Read the full explanation

You get a vector 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

    The function clampAll gets a vector of integers nums and two limits, low and high, with low never greater than high. It returns every number moved inside the limits, in the same order. A number below low becomes low, a number above high becomes high, and any other number stays as it is. The lesson does not allow a built-in min, max or clamp function, so the comparing is written by hand.

    For {12, -3, 7, 25} with limits 0 and 20 the answer is 12 0 7 20. For {-8, -1, 4} with limits -5 and 5 it is -5 -1 4. For {3, 9, 6} with both limits 6 it is 6 6 6. The tests print a vector as its values separated by spaces.

    Approach

    The work is split in two. The helper clamp deals with one number: given x and the limits, it returns x moved inside them. clampAll then only has to call the helper on every number and collect the answers. Each function has one job, which makes both easy to read and to test: the helper can be checked on single numbers before the loop exists.

    Inside the helper, two if statements are enough. A number below low returns low; a number above high returns high. A number that survives both is between the limits, so it is returned unchanged, and no else is needed because return already leaves the function.

    Following the first example

    With limits 0 and 20, the helper treats each number of {12, -3, 7, 25} like this:

    • 12 is not below 0 and not above 20, so it reaches the last line and stays 12;
    • -3 is below 0, so the first if returns 0;
    • 7 is inside, so it stays 7;
    • 25 passes the first test, fails the second by being above 20, and the second if returns 20.

    The loop collects these answers in order, which gives 12 0 7 20.

    Why a helper at all

    The loop could hold both if statements itself, but then it would do two jobs at once: walking the vector and deciding about one number. With a helper, the loop body is a single line and the rule for one number lives in one place. If the rule changes, only the helper changes. The helper can also be tried on its own, with calls like clamp(-3, 0, 20), which returns 0, and clamp(25, 0, 20), which returns 20.

    The C++ library has its own function called clamp that does the same job, which is why the lesson names the rule out loud and asks for the comparing to be written by hand. Inside the class, the plain name clamp means the class's own function.

    Step by step

    1. In clamp, check the lower limit: if x < low, return low.
    2. Check the upper limit: if x > high, return high.
    3. Return x for a number already inside.
    4. In clampAll, start with an empty vector<int> named clamped.
    5. Loop over nums with an int named num.
    6. Call the helper as clamp(num, low, high) and add the answer to the end of clamped with push_back.
    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;
        }
    
        vector<int> clampAll(vector<int> &nums, int low, int high) {
            vector<int> clamped;
            for (int num : nums) {
                clamped.push_back(clamp(num, low, high));
            }
            return clamped;
        }
    };
    

    Notes on the C++:

    • Both functions are members of Solution, so clampAll calls clamp by its plain name.
    • The vector is passed by reference, so it isn't copied; clampAll builds a new vector and leaves nums unchanged.
    • The helper takes its numbers by value. Changing x inside it would not affect the caller.
    • The first parameter of the helper is a plain int, copied on each call. That is the usual choice for small values; references matter for big containers like the vector.

    Complexity

    Time is O(n) for n numbers: the helper does two comparisons, which take constant time, and it runs once per number. Space is O(n) for the new vector. The helper itself uses no extra memory.

    Edge cases and common mistakes

    • Equal limits. With low == high == 6 every number is below, above or equal to 6, so every result is 6.
    • Negative limits. The comparisons work the same way: with limits -5 and 5, the number -8 becomes -5.
    • Returning inside the loop. Only the first number would come back.
    • Mixing up the limits. Returning high for a number below low sends -3 to 20 instead of 0.
    • Testing the limits wrongly. A number equal to a limit is already inside, so x <= low would work too but does extra work: it returns low, which is the same value. Using < and > keeps the meaning plain.
    • Writing into nums. The task asks for a new vector, and building clamped keeps the input as it was.

    Testing

    • {12, -3, 7, 25}, limits 0 and 20, gives 12 0 7 20.
    • {-8, -1, 4}, limits -5 and 5, gives -5 -1 4.
    • {3, 9, 6}, limits 6 and 6, gives 6 6 6.
    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free