Tutorialspoint
Problem
Solution
Submissions

Two Sum

Certification: Advanced Level Accuracy: 25% Submissions: 8 Points: 8

Write a C# function to solve the Two Sum problem. Given an array of integers 'nums'and an integer 'target', 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:
    • Because nums[0] + nums[1] = 2 + 7 = 9.
    • The indices of the two numbers that add up to the target are 0 and 1.
Example 2
  • Input: nums = [3, 2, 4], target = 6
  • Output: [1, 2]
  • Explanation:
    • Because nums[1] + nums[2] = 2 + 4 = 6.
    • The indices of the two numbers that add up to the target are 1 and 2.
Constraints
  • 2 ≤ nums.length ≤ 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • -10^9 ≤ target ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
NumberPwCPhillips
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

  • Using a brute force approach would be O(n²) time complexity
  • Use a hash map to reduce time complexity to O(n)
  • Track values you've seen and their indices as you iterate through the array
  • For each number, check if (target - current number) exists in the hash map
  • Return both indices when a match is found

Steps to solve by this approach:

 Step 1: Create a dictionary to store numbers and their indices.
 Step 2: Iterate through the array of numbers.
 Step 3: For each number, calculate its complement (target - current number).
 Step 4: Check if the complement exists in the dictionary.
 Step 5: If the complement exists, return the current index and the complement's index.
 Step 6: If no complement is found, add the current number and its index to the dictionary.
 Step 7: Continue until a solution is found.

Submitted Code :