Logo

dev-resources.site

for different kinds of informations.

LeetCode #1. Two Sum

Published at
10/1/2024
Categories
leetcode
competativeprogramming
dsa
Author
hectorw_tt
Categories
3 categories in total
leetcode
open
competativeprogramming
open
dsa
open
Author
10 person written this
hectorw_tt
open
LeetCode #1. Two Sum

This is the first post discussing my solutions to LeetCode problems.Check out my LeetCode profile and follow me on Twitter.

Problem
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].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

Discussion
The basic approach to solving this problem involves the use of a data structure known as a hash table. This table stores key : value pairs. Scanning from left to right, we check each index in the array and the value stored there. We subtract this value from the target value and check if the hash table has this as a key. If it does we return an array with the indices of both values which sum to target, otherwise we add to the hash table, the values stored at the current index and the current index. Once the scanning is done,we return null as the array has no existing values.

Algorithm

HashTable map = new HashTable();
for (var i =0; i<nums.length;i++){
var curr = nums[i];//value at current index
var other = target-curr;
if (map.has(other)) return new int[] {map.get(other),i};
map.put(curr,i);
}
return null;

Solution
Java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map <Integer,Integer> map = new HashMap<>();
        for (int i =0; i<nums.length;i++){
            int curr = nums[i];
            int other = target-curr;
            if (map.containsKey(other)){
                return new int[] {map.get(other),i};
            }
            map.put(curr,i);
        }
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

var twoSum = function(nums, target) {
 const map= new Map();
 const result=[];
 for(let i=0;i<nums.length;i++){
  if(map.has(target-nums[i])){
    result.push(map.get(target-nums[i]));
    result.push(i);
    return result;
  }else map.set(nums[i],i);
 }
 return result;   
};
Enter fullscreen mode Exit fullscreen mode

C#

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
      Dictionary<int,int> map= new Dictionary<int,int>(); 
      for(int i=0;i<nums.Length;i++){
        int curr= nums[i];
        int other= target-curr;
        if(map.ContainsKey(other)){
         int [] result= new int[2];
         result[0]=map[other];
         result[1]=i;
         return result;
        }else{
         if(map.ContainsKey(curr))map[curr]=i;
         else map.Add(curr,i);
        }
      } 
      return null;
    }
}  
Enter fullscreen mode Exit fullscreen mode

If you have any questions, comment below.

competativeprogramming Article's
30 articles in total
Favicon
What is a UX Competitive Audit — and How Do You Conduct One?
Favicon
Participating in a hackathon: My experience
Favicon
33rd day of my CP journey
Favicon
DAY 12 Tackling Math-Based Challenges
Favicon
55th day of my CP journey
Favicon
59th day of my CP journey
Favicon
51st day of my CP journey
Favicon
Day 4 :Everything You Need to Know About Functions in Python
Favicon
My journey in competitive programming
Favicon
60th day of my CP journey
Favicon
My journey in competitive programming
Favicon
Day 30: Competitive Programming Journal
Favicon
Day 31: Competitive Programming Journal
Favicon
LeetCode Review
Favicon
LeetCode 1762 - Buildings With an Ocean View: Three Approaches Explained (JAVA)
Favicon
LeetCode #1. Two Sum
Favicon
JAVA COLLECTION FRAMEWORK (ONLY INTERFACES)
Favicon
Read Input Until EOF (End-of-File) and Number Your Lines Effortlessly | Competitive Programming Java
Favicon
How Can I Setup Sublime Text Editor For Competitive Programming
Favicon
Enhance your algorithm skills: The ultimate guide to Atcoder in 2024
Favicon
Segment Tree-01
Favicon
Fewer Holidays, Increased Productivity? The Philippine Debate Heats Up
Favicon
Does solving/being able to solve hard code force challenges good for my career?
Favicon
C++ Code Snippets :)
Favicon
🧡How to take input in javascript using console (codechef)
Favicon
Contest Notifier - Browser Extension
Favicon
Solve Subarray Product Less Than K in javascript
Favicon
Longest Substring Without Repeating Characters
Favicon
āĻĒā§āĻ°ā§‹āĻ—ā§āĻ°āĻžāĻŽāĻŋāĻ‚ āĻ•āĻ¨ā§āĻŸā§‡āĻ¸ā§āĻŸ āĻāĻ° āĻœāĻ¨ā§āĻ¯ āĻļā§āĻ°ā§āĻ¤ā§‡ āĻ¯āĻž āĻ¯āĻž āĻļāĻŋāĻ–āĻŦā§‹ (āĻ•āĻŽāĻ¨ āĻŸāĻĒāĻŋāĻ•)
Favicon
āĻĒā§āĻ°ā§‹āĻ—ā§āĻ°āĻžāĻŽāĻŋāĻ‚ āĻĒā§āĻ°āĻ¤āĻŋāĻ¯ā§‹āĻ—āĻŋāĻ¤āĻžāĻ° āĻ¨āĻžāĻ¨āĻžāĻ¨ āĻ§āĻ°āĻ¨ āĨ¤

Featured ones: