Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Approach 2, Time complexity

Jul 18, 2024

I'm confused why would the worst case scenario for approach 2 be O(n^2) when using a Set in JavaScript since if the number already exists in the set, the add operation would just be ignored and the code would just early return true? So shouldn't the worst case scenario for approach 2 still be O(n)?

0

0

Comments
Comments
Shubham Vora
Shubham Voraa year ago

The concern about O(n^2) would only arise in very rare pathological cases where the hash function performs very poorly, which isn't typical for standard library implementations.

Please, read this:

`This complexity assumes that the hash functions used are efficient and...

On this page

Problem Statement

Examples

Solution

Approach 1: Brute Force

Approach 2: Using Hash Set

Approach 3: Sorting