Skip to content
DSA in JavaScript
← All patterns

Sort First

0/13 solved

What it is

Sort the data first so equal or related items sit next to each other, which turns a hard problem into a simple scan.

Used for

Duplicates, 3Sum, merging, closest pairs, scheduling.
nums
5
2
9
2
7

Step 1 of 4

Goal: does the list contain a duplicate? Checking every pair works but is slow. Idea: sort first, so equal numbers end up side by side.

You see

  • Duplicates, closeness or ordering questions
  • Pairs of neighbours matter
  • Brute force compares every pair

Learn it in

ArraysBubble SortSelection SortInsertion SortShellsortHeap SortCounting SortRadix SortBucket Sort

Template

// Sorting turns "compare every pair" into "compare neighbours".const hasDuplicate = nums => {  const s = [...nums].sort((a, b) => a - b);  return s.some((v, i) => i > 0 && v === s[i - 1]);};

Practice problems