0% found this document useful (0 votes)
45 views9 pages

Two Sum Problem: Java Solutions

The document discusses the 'Two Sum' problem, providing an optimal solution using a HashMap in Java, which achieves O(n) time complexity. It also presents a brute-force approach with O(n²) complexity and a two-pointer method after sorting the array, which has a time complexity of O(n log n). Additionally, it includes sample code and outputs for each approach, along with explanations of when to use each method.

Uploaded by

Akash Satdeve
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views9 pages

Two Sum Problem: Java Solutions

The document discusses the 'Two Sum' problem, providing an optimal solution using a HashMap in Java, which achieves O(n) time complexity. It also presents a brute-force approach with O(n²) complexity and a two-pointer method after sorting the array, which has a time complexity of O(n log n). Additionally, it includes sample code and outputs for each approach, along with explanations of when to use each method.

Uploaded by

Akash Satdeve
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link];

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 < [Link]; i++) {
int complement = target - nums[i];

// Check if complement is already in the map


if ([Link](complement)) {
return new int[] { [Link](complement), i };
}

// Store the current number and its index


[Link](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);

[Link]("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 [Link];

public class Example1 {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();

// Add key-value pairs


[Link]("Apple", 3);
[Link]("Banana", 5);
[Link]("Mango", 2);

// Print the entire map


[Link]("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 [Link];

public class Example2 {


public static void main(String[] args) {
HashMap<String, String> capitals = new HashMap<>();

[Link]("India", "New Delhi");


[Link]("USA", "Washington D.C.");
[Link]("Japan", "Tokyo");

// Access a value
[Link]("Capital of Japan: " + [Link]("Japan"));

// Update a value
[Link]("USA", "New York");
[Link]("Updated Capital of USA: " +
[Link]("USA"));
}
}

Output:
yaml
CopyEdit
Capital of Japan: Tokyo
Updated Capital of USA: New York

✅ Example 3: Looping through HashMap


java
CopyEdit
import [Link];
import [Link];

public class Example3 {


public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();

[Link](101, "Amit");
[Link](102, "Bhavna");
[Link](103, "Chirag");

[Link]("Student List:");

for ([Link]<Integer, String> entry : [Link]()) {


[Link]("Roll No: " + [Link]() + ", Name: " +
[Link]());
}
}
}

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 [Link] 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 [Link];

public class HashMapDemo {


public static void main(String[] args) {
HashMap<String, Integer> marks = new HashMap<>();

// Add key-value pairs


[Link]("Math", 90);
[Link]("Science", 85);
[Link]("English", 92);

// Retrieve a value by key


[Link]("Marks in Science: " + [Link]("Science"));

// Print all key-value pairs


[Link]("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 < [Link]; i++) {
for (int j = i + 1; j < [Link]; 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);

[Link]("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 [Link];

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 = [Link](nums, [Link]);
[Link](sortedNums);

int left = 0;
int right = [Link] - 1;

while (left < right) {


int sum = sortedNums[left] + sortedNums[right];

if (sum == target) {
[Link]("Pair found: " + sortedNums[left] + " +
" + sortedNums[right] + " = " + target);
return;
} else if (sum < target) {
left++;
} else {
right--;
}
}

[Link]("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.

Common questions

Powered by AI

In the "Two Sum" problem, the brute-force solution has a space complexity of O(1) since it does not use any significant additional data structures apart from loop variables . In contrast, the HashMap solution has a space complexity of O(n) because it potentially stores all n elements of the input array in the map to facilitate efficient look-up operations . The increased space usage in the HashMap solution is a trade-off for its improved time efficiency, allowing it to perform lookups in constant average time compared to the quadratic time performance of the brute-force method .

The brute-force method for solving the "Two Sum" problem, while inefficient, is preferable in educational contexts where understanding foundational algorithm concepts is important. It is also suitable for very small arrays where the computational cost of the inefficiency is minimal. Additionally, it may be used when constraints disallow the use of auxiliary data structures like HashMaps, or in environments where the overhead of managing extra data structures outweighs the benefits due to resource constraints .

The two-pointer technique, when applied to a sorted array for solving the "Two Sum" problem, can efficiently identify pairs that sum to a target without the need for additional data structures. However, this technique fails when it is crucial to track the original indices of the elements as sorting the array loses the original order of elements, thus losing track of their indices. The algorithm focuses solely on the values themselves, which means it is only useful when the indices are not required, or a problem can be reformulated to only care about the existence of such a pair .

Java’s HashMap is powerful due to its ability to store key-value pairs with fast average time complexity operations like get() and put(), and its ability to accommodate one null key and multiple null values . Despite these advantages, it imposes limitations such as its inherent unordered nature, which means keys and values are not stored in the order they are added, and any reliance on order must be managed externally. Furthermore, its operations are contingent upon having a good hash function to minimize collision, thereby requiring consideration of hash quality for ideal performance .

The internal mechanism of a HashMap contributes to its constant-time performance primarily through its use of hashing, where keys are passed through a hash function to compute a hash code that determines an index in an underlying array, known as a 'bucket', where the value is stored . This allows for quick retrieval since the desired key does not require scanning through each entry — instead, it provides direct access to its corresponding bucket. However, maintaining this efficiency requires a well-distributed hash function to minimize collisions, and providing appropriate handling for them, such as chaining, in which a linked list of entries is maintained in each bucket .

The HashMap-based solution to the "Two Sum" problem has a time complexity of O(n) because it processes each element of the input array in constant time on average by using the operations put and containsKey of the HashMap . Its space complexity is also O(n) since at most n elements are stored in the map. This method is considered optimal compared to alternatives, such as the brute-force approach with O(n²) time complexity, because it balances time efficiency with modest use of additional space to achieve linear time resolution of the problem, a substantial improvement for large data sets .

In Java's HashMap structure, keys operate under the Principle of Uniqueness, meaning that each key can only map to one value, and any attempt to insert a duplicate key will overwrite the existing value associated with that key . This ensures that each key is unique and simplifies operations such as get() by eliminating key duplicates. Consequently, it also requires developers to handle potential overwrites appropriately, often checking first if a key already exists or has a significant reason if updated values are permissible for the same key structure .

A HashMap in Java provides efficient retrieval of values through its use of hashing, which ideally allows operations like get() and put() to have a constant-time complexity O(1) under the assumption of a good hash function and minimal collisions . The trade-offs involve a higher memory usage due to the storage of keys and values, along with potentially increased complexity in handling collisions via methods like chaining or open addressing. Furthermore, although retrieval operations are generally fast, the worst-case time complexity can degrade to O(n) if many collisions occur, though this is rare if the load factor and initial capacity are managed well .

Using a HashMap to solve the "Two Sum" problem provides significant advantages over a brute-force approach. The HashMap approach allows checking for the complement (the number needed to reach the target sum) in constant average time O(1), making the overall time complexity O(n). This is more efficient compared to the brute-force method, which checks every possible pair and has a time complexity of O(n²) due to its nested loop structure . The use of extra space for storing elements in the HashMap results in a space complexity of O(n), but this trade-off is often preferred given the substantial improvement in time efficiency .

A developer might choose the Two-Pointer method with sorting over the HashMap approach when an application requires only determining the existence of a sum pair or returning the values themselves without needing index tracking. This method can be more memory efficient as it doesn't require storing additional structures aside from the sorted array copy. It also simplifies logic in scenarios where indices aren't needed, allowing for a straightforward implementation. Furthermore, its time complexity of O(n log n) due to sorting is fairly efficient, especially when constraints around index preservation or modification of the array are not issues .

You might also like