Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

123. Projection onto box constraints

easy
GeneralGeneral
senior

Projecting a vector onto box constraints is a common step in constrained optimization and gradient-based methods. In this problem, you’ll implement the projection operator that “clips” each coordinate into a valid interval.

Π[l,u](x)i=min(max(xi,li),ui)\Pi_{[l,u]}(x)_i = \min\left(\max(x_i,\, l_i),\, u_i\right)

Requirements

Implement the function

python

Rules:

  • Project each element x[i] independently into the interval [lower[i], upper[i]].
  • Return a NumPy array (don’t modify the input arrays in-place).
  • Use only NumPy and Python built-in libraries (no SciPy or other helpers).
  • Keep it efficient: use vectorized NumPy operations.

Example

python

Output:

python
Input Signature
ArgumentType
xnp.ndarray
lowernp.ndarray
uppernp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Use NumPy; no SciPy or helpers.

  • Return NumPy array.

  • Do not mutate inputs in-place.

Hint 1

Use np.clip(x, lower, upper) for a direct vectorized solution.

Hint 2

Alternatively, np.minimum(np.maximum(x, lower), upper) achieves the same result.

Roles
ML Engineer
AI Engineer
Data Scientist
Quantitative Analyst
Companies
GeneralGeneral
Levels
senior
entry
Tags
numpy
projection
clipping
constrained-optimization
32 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit