Algorithms and Data Structures · Junior · Question 62 of 75

Two Sum: find two numbers in an unsorted array that add up to target. What is the O(n) approach?

Explanation

One pass: if target - x was seen before, the pair is found; otherwise remember x and its index. Trying every pair is O(n²). Sorting gives O(n log n) and loses the original indices.

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 62

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz