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

Rewrite a Nested Loop as a Linear Scan

beginnerlayer B1 · Complexity analysis5 tests

The starter contains a working hasPairSum(nums, target): it returns true when two different positions in nums hold values adding up to target. It is correct and it is O(n^2). Rewrite it so it runs in O(n), keeping the exact same behaviour.

  • The two values must come from two different indices, but they may be equal values — [3, 3] with target 6 is true
  • A single element can never pair with itself: [4] with target 8 is false
  • Negative numbers and zero are allowed
  • One test runs 150,000 elements with no answer present. The quadratic version needs billions of comparisons there and will not finish — the linear one takes milliseconds

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