Introduction

Ready for an adventure in sorting algorithms? We will solve two fun problems: "Find the K-th Ordinal Number in a List" and "Count the Number of Flips in a List". These tasks portray situations where we need clever system design. Let's employ quick sort and merge sort to find efficient solutions. Buckle up!

Problem 1: Finding K-th Number in an Array

Imagine an array of numbers and a number k. Your mission is to discover the k-th smallest number in that array. k starts from 1, so when k = 1, we seek the smallest number; when k = 2, we want the second smallest, and onward.

Problem 1: Simple Solutions
Problem 1: Quick Sort to the Rescue

Quick sort can provide an optimal solution. We’ll divide the array into two parts using a pivot: the left side contains numbers less than the pivot, while the right side has all greater numbers.

If the pivot's position equals k, that's our answer! If not, we repeat the process on the necessary partition.

Problem 1: Building the Solution – Partition

It's coding time! Let’s make a function for partitioning in TypeScript.

TypeScript
function partition(arr: number[], low: number, high: number): number {
  const pivot = arr[low]; // Select pivot
  let i = low; // Index of smaller element

  for (let j = low + 1; j <= high; j++) {
    if (arr[j] <= pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements
    }
  }

  [arr[i], arr[low]] = [arr[low], arr[i]]; // Swap pivot
  return i; // Return pivot index
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal