Click4Ai

49.

Hard

Use Singular Value Decomposition (SVD) to approximate a matrix using only the top k singular values. This is the foundation for dimensionality reduction and data compression.

**Formula:** A_approx = U[:, :k] * diag(S[:k]) * Vt[:k, :]

Example:

Input: A = [[1, 2], [3, 4]], k = 1

Output: Rank-1 approximation of A (best low-rank approximation)

**Explanation:** SVD decomposes A = U * diag(S) * Vt. Using only the top k singular values gives the best rank-k approximation.

Constraints:

  • Use np.linalg.svd() to get U, S, Vt
  • k <= min(rows, cols)
  • Return the reconstructed matrix rounded to 2 decimal places
  • Test Cases

    Test Case 1
    Input: [[1, 2], [3, 4]], 1
    Expected: rank-1 approximation
    Test Case 2
    Input: [[1, 0], [0, 1]], 2
    Expected: [[1.0, 0.0], [0.0, 1.0]]
    Test Case 3
    Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], 2
    Expected: near-original matrix
    + 2 hidden test cases