Tutorialspoint
Problem
Solution
Submissions

Two Sum

Certification: Basic Level Accuracy: 9.68% Submissions: 31 Points: 5

Write a C program to find two numbers in an array that add up to a specific target. The function should return the indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example 1
  • Input: nums = [2, 7, 11, 15], target = 9
  • Output: [0, 1]
  • Explanation: The numbers at indices 0 and 1 are 2 and 7, and 2 + 7 = 9.
Example 2
  • Input: nums = [3, 2, 4], target = 6
  • Output: [1, 2]
  • Explanation: The numbers at indices 1 and 2 are 2 and 4, and 2 + 4 = 6.
Constraints
  • 2 ≤ nums.length ≤ 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • -10^9 ≤ target ≤ 10^9
  • Only one valid answer exists
  • Time Complexity: O(n)
  • Space Complexity: O(n)
NumberHCL TechnologiesSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • A brute force approach would be to check every possible pair, but this would be O(n²) time complexity
  • Use a hash table (or a map) to store each element's value and its index
  • For each element, check if the complement (target - current element) exists in the hash table
  • If the complement exists, you've found your pair
  • If not, add the current element to the hash table and continue

Steps to solve by this approach:

 Step 1: Initialize a result array to store the two indices.

 Step 2: Use a hash table to store visited elements and their indices.
 Step 3: Iterate through the array elements one by one.
 Step 4: For each element, calculate the complement (target - current element).
 Step 5: Check if the complement exists in the hash table.
 Step 6: If found, return the indices of the current element and its complement.
 Step 7: If not found, add the current element and its index to the hash table.

Submitted Code :