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

Back to Questions

58. Eigenvalues

easy
GeneralGeneral
senior

Compute the eigenvalues of a 2×2 matrix, which describe how the matrix scales vectors along special directions called eigenvectors. You’ll implement a tiny helper that returns both eigenvalues in a consistent order.

The eigenvalues λ\lambda and eigenvectors vv of a square matrix AA satisfy:

Av=λvA v = \lambda v

The eigenvalues are found by solving the characteristic equation:

det(AλI)=0\det(A - \lambda I) = 0

The eigenvalues of

A=[abcd]A=\begin{bmatrix}a & b\\ c & d\end{bmatrix}

are the roots of:

λ2(a+d)λ+(adbc)=0\lambda^2 - (a+d)\lambda + (ad-bc)=0

Requirements

Implement the function

python

Rules:

  • Compute eigenvalues using the closed-form quadratic formula (not np.linalg.eig).
  • Return a NumPy array of two floats, sorted from largest to smallest.
  • If the eigenvalues are equal, return [lambda, lambda].
  • Use only NumPy and Python built-in libraries.
  • Keep the implementation in this single function.

Example

python

Output:

python
Input Signature
ArgumentType
Anp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Use quadratic formula; no np.linalg.eig.

  • Input is 2x2 NumPy array.

  • Return NumPy array of two floats sorted non-increasing.

Hint 1

Start by unpacking the 2×2 matrix into scalars a, b, c, d, then compute the trace t = a + d and determinant det = a*d - b*c.

Hint 2

Use the characteristic polynomial: eigenvalues are roots of λ^2 - tλ + det = 0. Compute the discriminant Δ = t*t - 4*det, then apply the quadratic formula: (t ± sqrt(Δ)) / 2.

Hint 3

Return a NumPy array of two floats sorted largest to smallest. Don’t call np.linalg.eig; use np.sqrt for the square root.

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
eigenvalues
2x2-matrix
quadratic-formula
linear-algebra
14 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