Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Complexity analysis

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Complexity analysis

Count the Comparisons Exactly

beginnerlayer B1 · Complexity analysis4 tests

Consider this shape, which shows up inside selection sort, bubble sort and every 'check all pairs' scan:

  • for (let i = 0; i < n; i++)
  •   for (let j = i + 1; j < n; j++)
  •     // exactly one comparison happens here

Write countComparisons(n) returning the exact number of comparisons performed — not a Big-O class, the precise count.

  • n = 0 and n = 1 both perform 0 comparisons
  • Return a plain number
  • n can be in the hundreds of thousands, and the tests are strict about speed — so derive the closed form rather than actually running the two loops

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen