Two sum problem ( Without Repeating Numbers )
💻 coding

Two sum problem ( Without Repeating Numbers )

1 min read 150 words
1 min read
ShareWhatsAppPost on X
  • 1The Two Sum problem requires finding two indices of numbers that add up to a specific target without using the same element twice.
  • 2A dictionary is utilized to store the numbers and their indices for efficient lookup during the solution process.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(n) due to the use of a HashMap.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The Two Sum problem requires finding two indices of numbers that add up to a specific target without using the same element twice."

Two sum problem ( Without Repeating Numbers )

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.Easy
{
 class TwoSumSolution
 {
 public int[] TwoSum(int[] nums, int target)
 {
 var dict = new Dictionary<int, int>();
 var sumSetIndex = new int[2];
 for (int i=0;i<nums.Length;i++)
 { 
 dict.Add(nums[i], i); 
 }

 foreach (var num in nums)
 {
 if (dict.ContainsKey(num))
 { 
 if(dict.ContainsKey(target - num))
 {
 sumSetIndex[0] = dict[num];
 sumSetIndex[1] = dict[target - num]; 
 } 
 }
 }

 return sumSetIndex;
 }
 }
}

Time Complexity: O(n) - For a complete Iteration of N Numbers.

Space Complexity: O(n) - For HashMap

Detail: https://github.com/sumitc91/coding/blob/master/Coding/LeetCode/Easy/TwoSumSolutionDuplicateAllowed.cs

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 18 April 2020 · 1 min read · 150 words

Part of AskGif Blog · coding

You might also like