logo CodeStepByStep logo

kthSmallest

Language/Type: C++ Grid traversals interview
Related Links:

Write a function named kthSmallest that returns the kth smallest element value in a row/column-sorted Grid of integers. Your function accepts two parameters: a reference to a Grid where each row and each column are arranged in sorted order, and an integer k. You may assume that the arrays passed as parameters have the same dimensions. Consider the following matrix:

Grid<int> matrix {
    { 1,  2,  5, 14},
    {11, 15, 19, 22},
    {12, 16, 28, 32},
    {20, 22, 29, 35}
};

The matrix is not fully sorted, but notice that each row by itself is sorted, such as row 0, which contains 1, 2, 5, and 14. Each column is also sorted, such as column 0, which contains 1, 11, 12, and 20. Given the preceding matrix, the call of kthSmallest(matrix, 8) would return 16 since that is the array's 8th smallest element.

Assumptions: You may assume that the array's elements are properly row/column-sorted as described. You may assume that the matrix is square, meaning that it has the same number of rows and columns, and that each row has the same number of elements. You may assume that the matrix has at least 1 row and 1 column. You may assume that the value passed for k is between 1 and the number of elements in the matrix, inclusive.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.