Use Loop for Min/Max Instead of Sort
Install this skill
npx skills add vercel-labs/agent-skillsWorks across Claude Code, Cursor, Codex, Copilot & Antigravity
Finding the extrema in an array is a linear time operation that sorting unnecessarily complicates. When you sort a collection to retrieve the first or last item, you perform O(n log n) work. Iterating through the array once instead reduces this to O(n). This approach avoids memory-heavy operations like creating sorted copies of arrays. It is particularly critical when handling large datasets where sorting overhead causes latency or potential stack overflows. By comparing elements against tracked current min/max values during a single pass, you keep memory allocations low and CPU cycles minimal. This strategy is standard practice for optimizing hot code paths where latency sensitivity is prioritized over brevity. Replace sorting patterns with simple loops to ensure your JavaScript applications remain responsive regardless of the input data size.
When to Use This Skill
- •Finding the most recent timestamp in a list of log entries
- •Identifying price boundaries in a large dataset of products
- •Calculating the oldest and newest items in a transaction history
- •Processing telemetry data to find peak and trough values
How to Invoke This Skill
Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:
- “Optimize my code for finding the max value
- “Refactor this sort function for better performance
- “Why is my array sorting slow?
- “How to get min and max without sorting
- “Replace array sort for finding extreme values
What this skill does
- •Reduces time complexity from O(n log n) to O(n)
- •Eliminates unnecessary memory allocation from array copying
- •Prevents performance bottlenecks during large data processing
- •Enables simultaneous extraction of both min and max values
- •Ensures stable execution time regardless of array size
When not to use it
- ✕When the array is already sorted and needs no further processing
- ✕When you need to perform multiple distinct operations that require an ordered collection anyway
Example workflow
- Identify a bottleneck caused by array sorting
- Verify the array contains at least one item
- Initialize local variables to store the current min and max
- Perform a single loop across the array to compare elements
- Update variables only when a new value satisfies the condition
- Return the collected results after the loop finishes
Pitfalls & limitations
- !Failing to handle empty arrays which leads to undefined or null pointer errors
- !Miscalculating the logic when dealing with mixed types or null values
- !Over-reliance on Math.min/max spread syntax which can cause call stack overflows on massive arrays
FAQ
How it compares
While sorting provides a complete ordered list, this skill focuses strictly on extracting extrema, which reduces computational overhead by eliminating redundant data permutations.
📄 Full skill instructions — original source: vercel-labs/agent-skills
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)This works for small arrays but can be slower for very large arrays due to spread operator limitations. Use the loop approach for reliability.
How to Use This Skill Unit
Option A: Project-Specific (Recommended)
- Click "Download" above
- In your project, create the directory:
.agent/skills/js-min-max-loop/ - Save the file as
SKILL.md - The agent will automatically discover the skill based on its description.
Option B: Global Installation (All Agents)
Save the file to these locations to make it available across all projects:
- Claude Code:
~/.claude/skills/vercel-labs/agent-skills/js-min-max-loop/SKILL.md - Cursor:
~/.cursor/skills/vercel-labs/agent-skills/js-min-max-loop/SKILL.md - Antigravity:
~/.gemini/antigravity/skills/vercel-labs/agent-skills/js-min-max-loop/SKILL.md
🚀 Install with CLI:npx skills add vercel-labs/agent-skills