Home › Interview Questions › What is the time complexity of the two‑sum algorit…

What is the time complexity of the two‑sum algorithm that returns the indices of two numbers that add up to a target?

🟢 Easy Conceptual Fresher level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

The classic two‑sum problem asks for the indices of two numbers in an array that add up to a given target. A naive solution checks every pair of elements, resulting in O(n²) time. A more efficient approach uses a hash map (dictionary) to store each number’s index as you iterate through the array. For each element x, you compute its complement y = target – x and check whether y is already in the map. If it is, you return the stored index of y and the current index. Each lookup and insertion in the hash map is O(1) on average, so the entire pass over the array takes O(n) time. The space complexity is also O(n) because you may store up to n entries in the map. This hash‑based solution is the standard optimal answer for two‑sum and is often used in interview settings to demonstrate knowledge of hash tables and linear‑time algorithms.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500