LeetCode: Kth Smallest Element in a Sorted Matrix Solution

Flatten and sort

Approach

Steps:

  • Flatten the 2D-array in to 1D-array
  • Sort the array
  • Get the k-th element

Implementation

1/**
2 * @param {number[][]} matrix
3 * @param {number} k
4 * @return {number}
5 */
6var kthSmallest = function (matrix, k) {
7 return matrix.flat().sort((a, b) => a - b)[k - 1]
8}

Comments

Loading comments...

Tags

leetcode

sorting

matrix

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Reduce Array Size to The Half

Hash table, sort by occurences then greedily remove

Previous Post

LeetCode: Reshape the Matrix

Flat, reverse, and pop

HoningJS

Search Posts