Hello coders, Today we will see the solution ” Two Sum Leetcode Solution ” and both java and python programming languages.
Let’s see the problem statement.
Problem Statement:
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.
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]
Two Sum Leetcode Solution
Java
class Solution { public int[] twoSum(int[] nums, int target) { // inserted Value & Indices HashMap<Integer, Integer> map = new HashMap<>(); // Filling the HashMap for(int i = 0; i < nums.length; i++){ map.put(nums[i], i); } // Searching for the target indices for(int i = 0; i < nums.length; i++){ // I will get my first element Example:- [2,7,11,15], target = 9 int num = nums[i]; // I will get 2 int rem = target - num; // Calculating remaining value = 9 - 2 = 7 will get from here if(map.containsKey(rem)){ // Now I will check is on any index 7 present. int index = map.get(rem); // From here i will get the index for no. 7 if(index == i) continue; // By doing this i will handle the case to not select more then one of yourself. return new int[]{i, index}; // returning the array with their indices. } } return new int[]{}; // If we unable to found return empty array. } }
Python
from typing import List, Optional class Solution: def twoSum(self, nums: List[int], target: int) -> Optional[List[int]]: m = {} for i, num in enumerate(nums): x = target - num if x in m: return [m[x], i] m[num] = i
Disclaimer: This problem(Two Sum Leetcode solution) is originally created by Leetcode. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.