Coding Challenge Practice - Question 97

Published: (January 8, 2026 at 11:48 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Problem Description

The task is to find the k‑th largest element in an unsorted array that may contain duplicates.

The k‑th largest element is the element that would appear in position k if the array were sorted in descending order. It is equivalent to the ((n - k))-th smallest element, where (n) is the length of the array.

const target = arr.length - k;

Solution Overview

A quick‑select algorithm can locate the desired element without fully sorting the array.

  1. Choose a pivot – pick the last element of the current sub‑array.
  2. Partition – move all elements ≤ pivot to the left and the rest to the right.
  3. Compare the pivot index with target:
    • If they are equal, the pivot is the k‑th largest element.
    • If the pivot index is less than target, recurse on the right side.
    • If the pivot index is greater than target, recurse on the left side.

Only one side of the partition is explored at each step, giving average‑case linear time (O(n)).

Partition Function

function partition(left, right) {
  const pivot = arr[right];
  let i = left;

  for (let j = left; j  arr.length) return undefined;

  const target = arr.length - k;

  function partition(left, right) {
    const pivot = arr[right];
    let i = left;

    for (let j = left; j < right; j++) {
      if (arr[j] <= pivot) {
        [arr[i], arr[j]] = [arr[j], arr[i]];
        i++;
      }
    }
    [arr[i], arr[right]] = [arr[right], arr[i]];
    return i;
  }

  function quickSelect(left, right) {
    const pivotIndex = partition(left, right);

    if (pivotIndex === target) return arr[pivotIndex];
    if (pivotIndex < target) return quickSelect(pivotIndex + 1, right);
    return quickSelect(left, pivotIndex - 1);
  }

  return quickSelect(0, arr.length - 1);
}

That’s all folks!

Back to Blog

Related posts

Read more »

JavaScript Snippets: Split & Map

!Cover image for JavaScript Snippets: Split & Maphttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-...

Problem 8: Count Vowels

Hey everyone! 👋 Today, we're tackling a string manipulation problem: Counting Vowels. The goal is to write a function that counts the number of vowels in a giv...