Two Sum

Leetcode Problem Solution c#

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Constraints:

Screenshot 2022-08-23 at 10.29.55 PM.png

Approach:

Brute Force Method

Running two loops adding each number to get the target Time Complexity is O(N*N)

Code:

using System;

namespace TwoSum
{
    class Program
    {
        public int[] TwoSum(int[] nums, int target)
        {
            int[] a = new int[2];

            for(int i = 0; i < nums.Length; i++)
            {
                int x = nums[i];

                for(int j=i+1; j < nums.Length; j++)
                {

                    int y = nums[j];
                    if (x + y == target)
                    {
                        a[0] = i;
                        a[1] = j;
                        break;
                    }
                }
            }

            return a ;
        }
        static void Main(string[] args)
        {
            int[] nums = { 3, 3 };
            int target = 6;
            Program obj = new Program();
            int [] k = obj.TwoSum(nums, target);
            for(int i = 0; i < k.Length; i++)
            {
                Console.WriteLine(k[i]);
            }
        }
    }
}

There is another two pointer approach . Time Complexity is O(N)