In this article we will learn about LeetCode First question Two Sum in detail with optimized solution with Example.


  • 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.

Brute Force Code


Java Example

class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] {i, j}; } } } return new int[] {}; } } // 2023

C++ Example

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { if (nums[i] + nums[j] == target) { return {i, j}; } } } return {}; } }; // 2023

Complexity :

  • Time complexity: O(N2)
  • Space Complexity: O(1)

Optimized Code


Java Optimized Example

import java.util.HashMap; import java.util.Map; class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> numToIndex = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (numToIndex.containsKey(target - nums[i])) { return new int[] {numToIndex.get(target - nums[i]), i}; } numToIndex.put(nums[i], i); } return new int[] {}; } }

C++ Optimized Example

#include <unordered_map> class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mp; for(int i = 0; i < nums.size(); i++){ if(mp.find(target - nums[i]) == mp.end()) mp[nums[i]] = i; else return {mp[target - nums[i]], i}; } return {-1, -1}; } };

Complexity :

Time complexity: O(N);
Space Complexity: O(N);


I hope you like this Amazing Two Sum article.🙂


Also Read :


Admin

Share
Published by
Admin
Tags: DSA

Recent Posts

Blockchain Developer Roadmap

Blockchain is a shared, immutable ledger that facilitates the process of recording transactions and tracking assets…

4 weeks ago

Longest Substring Without Repeating Characters

In this article we will learn about LeetCode Third question Longest Substring Without Repeating Characters in detail…

7 months ago

Add Two Numbers

In this article we will learn about LeetCode Second question Add Two Numbers in detail with optimized…

7 months ago

Web Designing Roadmap 2023

In this amazing Web Designing Roadmap 2023 article, we’ll learn about A to Z about…

11 months ago

Android Developer Roadmap 2023

Android developer -- In this amazing Android Developer Roadmap article, we’ll learn about A to…

1 year ago

Full-Stack Developer Roadmap 2023

The roadmap for a full stack developer can vary depending on the individual's goals and…

1 year ago