LeetCode Problem: Two Sum
Problem Statement (Simplified):
Given an array of integers nums and an integer target, return the indices of the two numbers
such that they add up to the target.
✅ Java Code (Optimal Solution using HashMap)
import java.util.HashMap;
public class TwoSumSolution {
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
// Loop through the array
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
// Check if complement is already in the map
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
// Store the current number and its index
map.put(nums[i], i);
}
// If no solution is found
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
System.out.println("Indices: [" + result[0] + ", " + result[1] +
"]");
}
}
🧾 Sample Input:
java
CopyEdit
nums = [2, 7, 11, 15]
target = 9
✅ Output:
makefile
CopyEdit
Indices: [0, 1]
Explanation:
nums[0] + nums[1] = 2 + 7 = 9 → returns indices [0, 1].
🧠 Time & Space Complexity:
Time Complexity: O(n), where n = length of the array
Space Complexity: O(n), for storing elements in the HashMap
Let me know if you want:
Brute Force approach as well
Dry run of this solution
Code in C++, Python, or any other language
You said:
give me the simple example on hashmap 3 example with code and output
ChatGPT said:
Here are 3 simple and beginner-friendly Java examples of HashMap, each covering
different use cases, along with code and expected output:
✅ Example 1: Storing and Printing Key-Value Pairs
java
CopyEdit
import java.util.HashMap;
public class Example1 {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Add key-value pairs
map.put("Apple", 3);
map.put("Banana", 5);
map.put("Mango", 2);
// Print the entire map
System.out.println("Fruit Quantities: " + map);
}
}
Output:
yaml
CopyEdit
Fruit Quantities: {Banana=5, Apple=3, Mango=2}
Note: Order is not guaranteed in HashMap.
✅ Example 2: Accessing and Updating Values
java
CopyEdit
import java.util.HashMap;
public class Example2 {
public static void main(String[] args) {
HashMap<String, String> capitals = new HashMap<>();
capitals.put("India", "New Delhi");
capitals.put("USA", "Washington D.C.");
capitals.put("Japan", "Tokyo");
// Access a value
System.out.println("Capital of Japan: " + capitals.get("Japan"));
// Update a value
capitals.put("USA", "New York");
System.out.println("Updated Capital of USA: " +
capitals.get("USA"));
}
}
Output:
yaml
CopyEdit
Capital of Japan: Tokyo
Updated Capital of USA: New York
✅ Example 3: Looping through HashMap
java
CopyEdit
import java.util.HashMap;
import java.util.Map;
public class Example3 {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Amit");
students.put(102, "Bhavna");
students.put(103, "Chirag");
System.out.println("Student List:");
for (Map.Entry<Integer, String> entry : students.entrySet()) {
System.out.println("Roll No: " + entry.getKey() + ", Name: " +
entry.getValue());
}
}
}
Output:
yaml
CopyEdit
Student List:
Roll No: 101, Name: Amit
Roll No: 102, Name: Bhavna
Roll No: 103, Name: Chirag
If you want:
HashMap with duplicate key check
HashMap inside ArrayList
HashMap with objects as values
Just let me know — I’ll give you those examples too.
You said:
what is hashmap
ChatGPT said:
🔍 What is a HashMap in Java?
A HashMap in Java is a part of the java.util package that provides the basic
implementation of the Map interface. It stores data in the form of key-value pairs, where:
Key is used to uniquely identify each element.
Value is the data associated with that key.
✅ Key Features of HashMap:
Feature Description
Stores key-value
Each key maps to one value.
pairs
Only one value per key; if you add the same key again, it updates the
No duplicate keys
value.
Allows null
Allows one null key and multiple null values.
values
Unordered Doesn’t maintain insertion order.
Provides constant-time performance for basic operations (get() and
Fast access
put()), assuming a good hash function.
📦 Example:
java
CopyEdit
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Integer> marks = new HashMap<>();
// Add key-value pairs
marks.put("Math", 90);
marks.put("Science", 85);
marks.put("English", 92);
// Retrieve a value by key
System.out.println("Marks in Science: " + marks.get("Science"));
// Print all key-value pairs
System.out.println("All marks: " + marks);
}
}
🔷 Output:
yaml
CopyEdit
Marks in Science: 85
All marks: {Math=90, Science=85, English=92}
🧠 When to Use HashMap?
Use HashMap when:
You want to store unique keys and associate them with values.
You need fast lookup, insertion, or deletion.
Order of elements doesn’t matter.
If you want a visual diagram of how a HashMap works internally (like buckets, hashcode,
collision), let me know — I can explain that too.
You said:
ab is two sum example ko without hashmap kaise solve kre
ChatGPT said:
Great question!
The "Two Sum" problem can also be solved without using a HashMap, using a brute-force
approach. This method checks every possible pair in the array to see if their sum matches
the target.
✅ Brute-Force Java Code (Without HashMap)
java
CopyEdit
public class TwoSumWithoutHashMap {
public static int[] twoSum(int[] nums, int target) {
// Check every pair (i, j)
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
// If the pair sums up to target
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
// If no such pair is found
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
System.out.println("Indices: [" + result[0] + ", " + result[1] +
"]");
}
}
🧾 Sample Input:
java
CopyEdit
nums = [2, 7, 11, 15]
target = 9
✅ Output:
makefile
CopyEdit
Indices: [0, 1]
⏱ Time and Space Complexity:
Time Complexity: O(n²) → because we are checking every possible pair using two
nested loops.
Space Complexity: O(1) → no extra space used, only variables.
🧠 When to use this approach?
Use this only for small arrays or for learning purposes, because it's inefficient for large
input sizes. For interviews or production code, the HashMap approach is preferred due to its
O(n) performance.
Let me know if you want:
A dry run of this code
Or an approach using sorting + two pointers (works when array index return is not
required)
You said:
yes give me another approch
ChatGPT said:
Sure! Let's look at another efficient approach to solve the Two Sum problem — this time
using Sorting + Two Pointers method.
🚫 Important Note:
This method doesn't work directly if we need original indices (because sorting changes the
order).
But it is great when the problem asks only whether such a pair exists or to return the
actual values, not their indices.
✅ Approach 3: Two Pointers (with Sorting)
💡 Idea:
1. First, sort the array.
2. Use two pointers: one at the start (left) and one at the end (right).
3. Move pointers inward depending on the sum:
o If sum is too small → move left forward.
o If sum is too big → move right backward.
o If equal → return the pair.
✅ Java Code:
java
CopyEdit
import java.util.Arrays;
public class TwoSumSorted {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
// Copy and sort the array (we lose original indices here)
int[] sortedNums = Arrays.copyOf(nums, nums.length);
Arrays.sort(sortedNums);
int left = 0;
int right = sortedNums.length - 1;
while (left < right) {
int sum = sortedNums[left] + sortedNums[right];
if (sum == target) {
System.out.println("Pair found: " + sortedNums[left] + " +
" + sortedNums[right] + " = " + target);
return;
} else if (sum < target) {
left++;
} else {
right--;
}
}
System.out.println("No pair found.");
}
}
🧾 Sample Input:
ini
CopyEdit
nums = [2, 7, 11, 15]
target = 9
✅ Output:
yaml
CopyEdit
Pair found: 2 + 7 = 9
⏱ Time and Space Complexity:
Time: O(n log n) for sorting + O(n) for two-pointer scan → Total: O(n log n)
Space: O(n) (for copying original array)
✅ When to Use This:
You don’t need to return indices, just check existence or return the values.
You need a more efficient solution than brute-force but can't use HashMap.
🧠 Bonus:
If the question allows modifying the input array and doesn’t require indices — this is a very
clean and fast solution.