Leetcode

00001. Leetcode: Two Sum – Problem and Solutions

The Two Sum Problem

The Two Sum problem is a classic algorithmic problem from leetcode that goes like this: given an array of integers nums and an integer target, return 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.

Solution 1: Two Sum with Hash Table

Solution
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        Dictionary<int, int> table = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; i++)
        {
            int complement = target - nums[i];
            if (table.ContainsKey(complement))
            {
                return new int[] { table[complement], i };
            }
            table[nums[i]] = i;
        }
        return null;
    }
}

Explanation:

This solution utilizes a hash table to store the complement of each element along with its index. The algorithm iterates through the array, and for each element, it checks if the complement (the difference between the target and the current element) exists in the hash table. If it does, the function returns the indices of the two elements that add up to the target.

Pros:

  • Time complexity: O(n) – the algorithm makes a single pass through the array.
  • Space complexity: O(n) – additional space is used for the hash table.

Cons:

  • Relies on additional space due to the hash table.

Solution 2: Two Sum with Nested Loop

public class Solution {
    public int[] TwoSum(int[] nums, int target) {

            int n = nums.Length;

            for (int i = 0; i < n - 1; i++)
            {
                for (int j = i + 1; j < n; j++)
                {      
                    if (nums[i] + nums[j] == target)
                    {
                        return new int[] { i, j };
                    }
                }
            }
            return null;
    }
}

Explanation:

This solution uses a nested loop to iterate through pairs of elements in the array, checking if their sum equals the target. If a match is found, the function returns the indices of the two elements.

Pros:

  • Simple and easy to understand.
  • No additional space used.

Cons:

  • Time complexity: O(n^2) – the algorithm has nested loops, resulting in higher time complexity for larger arrays.

Conclusion

Both solutions provide a valid approach to solving the Two Sum problem, but the choice between them depends on the specific requirements of your use case. The hash table solution offers a more efficient O(n) time complexity, making it suitable for larger datasets, while the nested loop solution is simpler and may be sufficient for smaller arrays.

Remember to consider the trade-offs between time and space complexity when choosing an algorithm for your particular scenario.

Danilo Cavalcante

Working with web development since 2005, currently as a senior programmer analyst. Development, maintenance, and integration of systems in C#, ASP.Net, ASP.Net MVC, .Net Core, Web API, WebService, Integrations (SOAP and REST), Object-Oriented Programming, DDD, SQL, Git, and JavaScript

Recent Posts

Collections and LINQ Queries in C#

In modern C# programming, working with data collections is a common task. Understanding how to…

2 days ago

Exception Handling in C#: try-catch, finally, and Custom Exceptions

Exception handling is a critical part of writing robust and maintainable C# applications. It allows…

3 days ago

Do Docker Containers Take Up Space?

One of the common questions among Docker users is whether Docker containers consume disk space.…

6 months ago

How to Use “Order By” in C#

Sorting data is a common operation in programming, allowing you to organize information in a…

6 months ago

How to Split a String into an Array in C#

Splitting a string into an array of substrings is a common operation in C# programming,…

6 months ago

Starting the Docker Daemon: A Step-by-Step Guide

Starting the Docker daemon is the first step towards managing Docker containers and images on…

6 months ago